Zamin Docs

Standard Library Reference

Zamin ships with a comprehensive standard library. Built-in functions are available globally, and all other modules are available without import. This page covers every module and every function in the standard library.

Built-in Functions

These functions are available globally in every Zamin script without any import.

Functions

FunctionSignatureDescription
printprint(*args)Prints all arguments to stdout with no trailing newline. Multiple arguments are printed consecutively.
printlnprintln(*args)Same as print but appends a newline after all arguments.
inputinput(prompt?)Prints the optional prompt, reads a line from stdin, and returns it as a string (trimmed).
typetype(val)Returns the type name of val as a string (e.g. "int", "string", "list").
lenlen(val)Returns the length of a string, list, dict, or set.

Examples

Zamin
print("Hello, Zamin!");
print("the answer is", 42);
println("this has a newline");

let name = input("Enter your name: ");
print(f"Hello, {name}!");

print(type(42));          // int
print(type("hello"));     // string
print(type([1, 2, 3]));   // list
print(type(true));        // bool

print(len("hello"));      // 5
print(len([1, 2, 3]));    // 3

math Module

Mathematical functions and constants. All trigonometric functions use radians.

Functions

FunctionSignatureDescription
sqrtmath.sqrt(x)Returns the square root of x.
powmath.pow(x, y)Returns x raised to the power y.
absmath.abs(x)Returns the absolute value of x.
sinmath.sin(x)Returns the sine of x (radians).
cosmath.cos(x)Returns the cosine of x (radians).
tanmath.tan(x)Returns the tangent of x (radians).
pimath.piThe constant pi (3.14159...).
emath.eEuler's number e (2.71828...).

Examples

Zamin
print(math.sqrt(25));            // 5.0
print(math.pow(2, 10));          // 1024.0
print(math.abs(-42));            // 42.0

print(math.sin(math.pi / 2));    // 1.0
print(math.cos(0));              // 1.0
print(math.tan(math.pi / 4));    // ~1.0

print(math.pi);                  // 3.141592653589793
print(math.e);                   // 2.718281828459045

string Module

Functions for string manipulation. All functions take a string as the first argument.

Functions

FunctionSignatureDescription
lenstring.len(s)Returns the byte length of s.
upperstring.upper(s)Returns an uppercase copy of s.
lowerstring.lower(s)Returns a lowercase copy of s.
trimstring.trim(s)Removes leading and trailing whitespace from s.
trim_startstring.trim_start(s)Removes leading whitespace from s.
trim_endstring.trim_end(s)Removes trailing whitespace from s.
splitstring.split(s, delim?)Splits s on delim (default: space). Returns a list.
joinstring.join(list, sep?)Joins list items into a string with optional separator.
containsstring.contains(s, sub)Returns true if s contains sub.
starts_withstring.starts_with(s, prefix)Returns true if s starts with prefix.
ends_withstring.ends_with(s, suffix)Returns true if s ends with suffix.
replacestring.replace(s, from, to)Replaces all occurrences of from with to in s.
reversestring.reverse(s)Returns a reversed copy of s.
repeatstring.repeat(s, n)Returns s repeated n times.
substringstring.substring(s, start, end?)Returns the substring from start to end (or end of string).
bytesstring.bytes(s)Returns a list of integer byte values for s.
from_bytesstring.from_bytes(list)Converts a list of integers to a string.

Examples

Zamin
print(string.len("hello"));                          // 5
print(string.upper("hello"));                        // "HELLO"
print(string.lower("HELLO"));                        // "hello"
print(string.trim("  hi  "));                        // "hi"
print(string.trim_start("  hi  "));                  // "hi  "
print(string.trim_end("  hi  "));                    // "  hi"

print(string.split("a,b,c", ","));                   // ["a", "b", "c"]
print(string.split("hello world"));                  // ["hello", "world"]
print(string.join(["a", "b", "c"], ", "));           // "a, b, c"

print(string.contains("hello world", "world"));      // true
print(string.starts_with("hello", "hel"));           // true
print(string.ends_with("hello", "llo"));             // true
print(string.replace("a-b-c", "-", ":"));            // "a:b:c"

print(string.reverse("abc"));                        // "cba"
print(string.repeat("x", 3));                        // "xxx"
print(string.substring("hello", 1, 4));              // "ell"

let bytes = string.bytes("ABC");                     // [65, 66, 67]
print(string.from_bytes(bytes));                     // "ABC"

fs Module

File system operations for reading and writing files.

Functions

FunctionSignatureDescription
readfs.read(path)Reads the entire file at path and returns its contents as a string.
writefs.write(path, content)Writes content to the file at path, overwriting existing content. Returns true.
existsfs.exists(path)Returns true if path exists on disk.
mkdirfs.mkdir(path)Creates a directory (and parents) at path. Returns true.

Examples

Zamin
fs.write("hello.txt", "Hello, Zamin!");
let content = fs.read("hello.txt");
print(content);                         // Hello, Zamin!

print(fs.exists("hello.txt"));          // true
print(fs.exists("missing.txt"));        // false

fs.mkdir("output/data");
fs.write("output/data/result.txt", "done");

os Module

Operating system interaction: environment variables, arguments, and shell commands.

Functions

FunctionSignatureDescription
cwdos.cwd()Returns the current working directory as a string.
argsos.args()Returns a list of command-line arguments.
getenvos.getenv(name)Returns the value of the environment variable name, or nil if not set.
nameos.name()Returns the OS name (e.g. "linux", "windows").
systemos.system(cmd)Runs cmd via the system shell. Returns the exit code.

Examples

Zamin
print(os.cwd());                        // /home/user/project
print(os.name());                       // "linux"

let args = os.args();
print(f"You are running: {args[0]}");

let home = os.getenv("HOME");
print(f"Home dir: {home}");

let status = os.system("echo hello");
print(f"Exit code: {status}");           // 0

json Module

JSON parsing and serialization. Supports strings, numbers, booleans, null, arrays, and objects.

Functions

FunctionSignatureDescription
parsejson.parse(s)Parses a JSON string into a Zamin value (dict, list, etc.).
loadsjson.loads(s)Alias for json.parse.
stringifyjson.stringify(val)Converts a Zamin value to a JSON string.
dumpsjson.dumps(val)Alias for json.stringify.
dumpjson.dump(val, path)Writes val as JSON to the file at path.
loadjson.load(path)Reads and parses a JSON file at path.
prettyjson.pretty(val, indent?)Returns a pretty-printed JSON string with configurable indentation (default: 2 spaces).

Examples

Zamin
let data = json.parse('{"name": "Zamin", "version": 1.0}');
print(data["name"]);                    // Zamin

let encoded = json.stringify(data);
print(encoded);                         // {"name":"Zamin","version":1.0}

let pretty = json.pretty(data);
print(pretty);
// {
//   "name": "Zamin",
//   "version": 1.0
// }

json.dump(data, "config.json");
let loaded = json.load("config.json");

re Module

Regular expression support using Rust's regex syntax. Patterns are cached for repeated use.

Functions

FunctionSignatureDescription
findre.find(pattern, text)Returns the first match of pattern in text, or nil.
is_matchre.is_match(pattern, text)Returns true if pattern matches somewhere in text.
splitre.split(pattern, text)Splits text on the regex pattern. Returns a list.
subre.sub(pattern, replacement, text)Replaces the first match of pattern with replacement.
sub_allre.sub_all(pattern, replacement, text)Replaces all matches of pattern with replacement.
find_allre.find_all(pattern, text)Returns a list of all matches of pattern in text.
capturesre.captures(pattern, text)Returns a list of capture groups (including group 0), or nil.

Examples

Zamin
let text = "Contact: user@example.com, admin@test.com";

let emails = re.find_all(r"[\w.]+@[\w.]+", text);
print(emails);                          // ["user@example.com", "admin@test.com"]

let first = re.find(r"\d+", "abc 123 def 456");
print(first);                           // "123"

print(re.is_match(r"\d+", "abc 123"));  // true

let cleaned = re.sub(r"\d+", "#", "abc 123 def 456");
print(cleaned);                         // "abc # def 456"

let all_clean = re.sub_all(r"\d+", "#", "abc 123 def 456");
print(all_clean);                       // "abc # def #"

let parts = re.split(r"[,;]", "a,b;c");
print(parts);                           // ["a", "b", "c"]

let caps = re.captures(r"(\w+)@(\w+)", "user@example.com");
print(caps);                           // ["user@example.com", "user", "example.com"]

http Module

HTTP client for making requests. All functions return a response dict with keys status (int), headers (dict), and body (string).

Functions

FunctionSignatureDescription
gethttp.get(url)Sends a GET request to url. Returns a response dict.
posthttp.post(url, body)Sends a POST request with body (string) to url. Returns a response dict.
requesthttp.request(method, url, headers?, body?)Sends a request with any HTTP method. headers is a dict, body is a string.

Response Dict

KeyTypeDescription
statusintHTTP status code (e.g. 200, 404).
headersdictResponse headers as key-value pairs.
bodystringThe response body as a string.

Examples

Zamin
let resp = http.get("https://api.github.com/repos/young-developer90/zamin");
print(resp.status);                     // 200
print(resp.body);                       // JSON string

let resp2 = http.post("https://httpbin.org/post",
    json.stringify({"key": "value"})
);
print(resp2.status);

let resp3 = http.request("GET", "https://httpbin.org/get",
    {"Accept": "application/json"}
);
print(resp3.headers["content-type"]);

url Module

URL parsing, encoding, decoding, and joining.

Functions

FunctionSignatureDescription
parseurl.parse(url_string)Parses a URL string into a dict with keys: scheme, host, path, query, fragment, port, query_params.
encodeurl.encode(text)URL-encodes the given text (percent encoding).
decodeurl.decode(text)URL-decodes the given percent-encoded text.
joinurl.join(base, relative)Resolves a relative URL against a base URL. Returns the joined URL string.

Examples

Zamin
let parsed = url.parse("https://example.com:8080/path?q=1#section");
print(parsed["scheme"]);                // "https"
print(parsed["host"]);                  // "example.com"
print(parsed["port"]);                  // 8080
print(parsed["path"]);                  // "/path"

let encoded = url.encode("hello world&foo=bar");
print(encoded);                         // "hello%20world%26foo%3Dbar"
print(url.decode(encoded));             // "hello world&foo=bar"

let joined = url.join("https://example.com/api", "users/1");
print(joined);                          // "https://example.com/api/users/1"

csv Module

CSV parsing and serialization. Supports quoted fields and escaped commas.

Functions

FunctionSignatureDescription
parsecsv.parse(text)Parses CSV text into a list of rows (each row is a list of strings).
parse_headercsv.parse_header(text)Parses CSV text using the first row as headers. Returns a list of dicts.
stringifycsv.stringify(rows)Converts a list of rows (lists or dicts) to CSV text.
loadcsv.load(path)Reads and parses a CSV file at path.
savecsv.save(path, rows)Saves a list of rows to a CSV file at path.

Examples

Zamin
let csv_text = "name,age\nAlice,30\nBob,25";
let rows = csv.parse(csv_text);
print(rows);                            // [["name","age"],["Alice","30"],["Bob","25"]]

let records = csv.parse_header(csv_text);
print(records[0]["name"]);              // "Alice"
print(records[0]["age"]);               // "30"

let output = csv.stringify([["x", "y"], ["1", "2"], ["3", "4"]]);
print(output);

csv.save("output.csv", [["a", "b"], ["1", "2"]]);
let data = csv.load("output.csv");

datetime Module

Date and time functions. Datetime values are represented as dicts with keys: year, month, day, hour, minute, second, unix.

Functions

FunctionSignatureDescription
nowdatetime.now()Returns the current date/time as a datetime dict.
from_unixdatetime.from_unix(timestamp)Converts a Unix timestamp (seconds) to a datetime dict.
formatdatetime.format(dt, fmt)Formats a datetime dict using format specifiers. Returns a string.
parsedatetime.parse(s, fmt)Parses a date string using format specifiers. Returns a datetime dict.
unixdatetime.unix(dt)Returns the Unix timestamp from a datetime dict.

Format Specifiers

SpecMeaningExample
%Y4-digit year2026
%y2-digit year26
%mMonth (01-12)07
%dDay (01-31)16
%HHour (00-23)14
%MMinute (00-59)30
%SSecond (00-59)05

Examples

Zamin
let now = datetime.now();
print(now["year"]);                     // 2026
print(now["month"]);                    // 7
print(now["day"]);                      // 16

let formatted = datetime.format(now, "%Y-%m-%d %H:%M:%S");
print(formatted);                       // "2026-07-16 14:30:05"

let short = datetime.format(now, "%m/%d/%Y");
print(short);                           // "07/16/2026"

let parsed = datetime.parse("2026-01-15", "%Y-%m-%d");
print(parsed["year"]);                  // 2026
print(parsed["month"]);                 // 1

let ts = datetime.from_unix(1700000000);
print(datetime.format(ts, "%Y-%m-%d")); // "2023-11-14"

print(datetime.unix(now));              // current timestamp

stats Module

Statistical functions for lists of numbers.

Functions

FunctionSignatureDescription
sumstats.sum(list)Returns the sum of all elements.
meanstats.mean(list)Returns the arithmetic mean.
medianstats.median(list)Returns the median value.
modestats.mode(list)Returns a list of the most frequent values.
variancestats.variance(list)Returns the sample variance.
stdstats.std(list)Returns the sample standard deviation.
minstats.min(list)Returns the minimum value.
maxstats.max(list)Returns the maximum value.
quantilestats.quantile(list, q)Returns the q-th quantile (q between 0 and 1).
covariancestats.covariance(x, y)Returns the sample covariance of two lists.
correlationstats.correlation(x, y)Returns the Pearson correlation coefficient of two lists.
normalizestats.normalize(list)Normalizes values to the [0, 1] range. Returns a list.
standardizestats.standardize(list)Z-score standardization (zero mean, unit variance). Returns a list.

Examples

Zamin
let data = [1.0, 2.0, 3.0, 4.0, 5.0];

print(stats.sum(data));                 // 15.0
print(stats.mean(data));                // 3.0
print(stats.median(data));              // 3.0
print(stats.std(data));                 // ~1.5811
print(stats.variance(data));            // 2.5
print(stats.min(data));                 // 1.0
print(stats.max(data));                 // 5.0

print(stats.quantile(data, 0.25));      // 2.0 (25th percentile)
print(stats.quantile(data, 0.75));      // 4.0 (75th percentile)

let x = [1.0, 2.0, 3.0, 4.0, 5.0];
let y = [2.0, 4.0, 5.0, 4.0, 5.0];
print(stats.correlation(x, y));         // ~0.86
print(stats.covariance(x, y));          // ~1.5

print(stats.normalize(data));           // [0.0, 0.25, 0.5, 0.75, 1.0]
print(stats.standardize(data));         // z-scored values

hashlib Module

Cryptographic hash functions and encoding/decoding utilities.

Functions

FunctionSignatureDescription
sha256hashlib.sha256(data)Returns the SHA-256 hash of data as a hex string.
sha512hashlib.sha512(data)Returns the SHA-512 hash of data as a hex string.
md5hashlib.md5(data)Returns the MD5 hash of data as a hex string.
sha1hashlib.sha1(data)Returns the SHA-1 hash of data as a hex string.
base64_encodehashlib.base64_encode(data)Base64-encodes data.
base64_decodehashlib.base64_decode(data)Base64-decodes data.
hex_encodehashlib.hex_encode(data)Hex-encodes the raw bytes of data.
hex_decodehashlib.hex_decode(data)Hex-decodes a hex string back to raw bytes.

Examples

Zamin
print(hashlib.sha256("hello"));
// 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

print(hashlib.md5("hello"));
// 5d41402abc4b2a76b9719d911017c592

print(hashlib.sha1("hello"));
// aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d

let encoded = hashlib.base64_encode("hello");
print(encoded);                         // "aGVsbG8="
print(hashlib.base64_decode(encoded));  // "hello"

let hex = hashlib.hex_encode("ABC");
print(hex);                             // "414243"
print(hashlib.hex_decode(hex));         // "ABC"

logging Module

Structured logging with configurable log levels. Output goes to stderr.

Functions

FunctionSignatureDescription
debuglogging.debug(*args)Logs a DEBUG message (only shown if level is DEBUG).
infologging.info(*args)Logs an INFO message (shown at INFO level and below).
warnlogging.warn(*args)Logs a WARN message (shown at WARN level and below).
errorlogging.error(*args)Logs an ERROR message (always shown).
set_levellogging.set_level(level)Sets the minimum log level. Accepts: "DEBUG", "INFO", "WARN", "ERROR".
basic_configlogging.basic_config(level?)Initializes logging with an optional level (default: DEBUG).

Examples

Zamin
logging.set_level("DEBUG");

logging.debug("Starting application");
logging.info("Server running on port 8080");
logging.warn("Disk space low");
logging.error("Connection failed");

// Output format: [timestamp][LEVEL] message

logging.set_level("WARN");
logging.debug("this is hidden");
logging.warn("this is visible");

subprocess Module

Run external commands and capture their output.

Functions

FunctionSignatureDescription
runsubprocess.run(cmd)Runs cmd as a direct command. Returns a result dict with returncode, stdout, and stderr.
run_shellsubprocess.run_shell(cmd)Runs cmd via the system shell (sh -c or cmd /C). Returns a result dict.
run_outputsubprocess.run_output(cmd)Runs cmd and returns only the stdout as a string.
run_shell_outputsubprocess.run_shell_output(cmd)Runs cmd via shell and returns only the stdout as a string.

Result Dict

KeyTypeDescription
returncodeintThe exit code of the process.
stdoutstringCaptured standard output.
stderrstringCaptured standard error.

Examples

Zamin
let result = subprocess.run("echo hello");
print(result["returncode"]);            // 0
print(result["stdout"]);                // "hello\n"

let output = subprocess.run_output("whoami");
print(output);                          // "current username"

let ls = subprocess.run_shell_output("ls -la");
print(ls);

let err = subprocess.run_shell("cat /nonexistent");
print(err["stderr"]);                   // error message
print(err["returncode"]);               // non-zero

path Module

File path manipulation and filesystem operations. Paths use forward slashes internally.

Functions

FunctionSignatureDescription
joinpath.join(*parts)Joins path components with /.
basenamepath.basename(p)Returns the last component of a path (filename).
dirnamepath.dirname(p)Returns the directory portion of a path.
extpath.ext(p)Returns the file extension (without the dot).
is_filepath.is_file(p)Returns true if p is a regular file.
is_dirpath.is_dir(p)Returns true if p is a directory.
sizepath.size(p)Returns the file size in bytes.
renamepath.rename(old, new)Renames/moves a file from old to new.
copypath.copy(src, dst)Copies a file from src to dst.
removepath.remove(p)Deletes the file at p.
remove_dirpath.remove_dir(p)Recursively deletes the directory at p.
list_dirpath.list_dir(p?)Returns a list of filenames in the directory (default: ".").
walkpath.walk(p?)Recursively walks a directory. Returns a list of all file paths.
abspath.abs(p)Returns the absolute path for p.
splitpath.split(p)Splits a path into [directory, basename].

Examples

Zamin
print(path.join("dir", "sub", "file.txt"));    // "dir/sub/file.txt"
print(path.basename("/usr/local/bin/bash"));   // "bash"
print(path.dirname("/usr/local/bin/bash"));    // "/usr/local/bin"
print(path.ext("document.txt"));               // "txt"
print(path.abs("."));                          // "/home/user/project"

let [dir, name] = path.split("/usr/local/bin");
print(dir);                             // "/usr/local/bin"
print(name);                            // "bin"

fs.mkdir("test_dir");
fs.write("test_dir/a.txt", "hello");
fs.write("test_dir/b.txt", "world");

print(path.is_file("test_dir/a.txt"));  // true
print(path.is_dir("test_dir"));          // true
print(path.size("test_dir/a.txt"));      // 5

let files = path.list_dir("test_dir");
print(files);                           // ["a.txt", "b.txt"]

let all = path.walk(".");
path.rename("test_dir/a.txt", "test_dir/c.txt");
path.copy("test_dir/b.txt", "test_dir/d.txt");
path.remove("test_dir/d.txt");
path.remove_dir("test_dir");

collections Module

Specialized collection types and utilities for counting, grouping, and deque operations.

Functions

FunctionSignatureDescription
Countercollections.Counter(list_or_string)Returns a dict mapping each element to its frequency count.
dequecollections.deque(list?)Creates a double-ended queue from an optional list.
push_leftcollections.push_left(deque, val)Pushes val to the front of the deque.
pop_leftcollections.pop_left(deque)Removes and returns the front element of the deque.
push_rightcollections.push_right(deque, val)Pushes val to the back of the deque.
pop_rightcollections.pop_right(deque)Removes and returns the back element of the deque.
group_bycollections.group_by(list, key_func)Groups elements by the result of key_func. Returns a dict of lists.
flattencollections.flatten(list)Flattens a nested list of lists into a single list.

Examples

Zamin
// Counter
let words = ["apple", "banana", "apple", "cherry", "banana", "apple"];
let counts = collections.Counter(words);
print(counts);                          // {"apple": 3, "banana": 2, "cherry": 1}

let letters = collections.Counter("hello");
print(letters);                         // {"h": 1, "e": 1, "l": 2, "o": 1}

// Deque operations
let dq = collections.deque([1, 2, 3]);
collections.push_left(dq, 0);
collections.push_right(dq, 4);
print(dq);                              // [0, 1, 2, 3, 4]
print(collections.pop_left(dq));        // 0
print(collections.pop_right(dq));       // 4

// group_by
let people = ["Alice", "Bob", "Anna", "Ben"];
let groups = collections.group_by(people, |name| string.upper(string.substring(name, 0, 1)));
print(groups);                          // {"A": ["Alice", "Anna"], "B": ["Bob", "Ben"]}

// flatten
let nested = [[1, 2], [3, [4, 5]], 6];
print(collections.flatten(nested));     // [1, 2, 3, 4, 5, 6]

itertools Module

Functional programming utilities for working with iterators and collections.

Functions

FunctionSignatureDescription
chainitertools.chain(*lists)Concatenates multiple lists into one.
zipitertools.zip(*lists)Zips multiple lists into a list of sub-lists (truncated to shortest).
enumerateitertools.enumerate(list)Returns a list of [index, value] pairs.
mapitertools.map(fn, list)Applies fn to each element. Returns a new list.
filteritertools.filter(fn, list)Keeps elements where fn returns truthy. Returns a new list.
reduceitertools.reduce(fn, list, init?)Reduces the list using a binary function. Optional initial value.
takeitertools.take(n, list)Returns the first n elements.
dropitertools.drop(n, list)Returns all but the first n elements.
sliceitertools.slice(list, start, end, step?)Returns a slice from start to end with optional step.
uniqueitertools.unique(list)Removes duplicates, preserving order.
reverseitertools.reverse(list)Returns a reversed copy of the list.
countitertools.count(start?, step?)Returns an infinite list of numbers (capped at 10,000). Default start=0, step=1.
repeatitertools.repeat(val, n)Returns a list containing val repeated n times.
productitertools.product(*lists)Computes the Cartesian product of multiple lists.
anyitertools.any(list, fn?)Returns true if any element is truthy (or passes fn).
allitertools.all(list, fn?)Returns true if all elements are truthy (or pass fn).
sorteditertools.sorted(list, key_fn?)Returns a sorted copy. Optional key function for custom sort order.
identityitertools.identity(val)Returns its argument unchanged.
composeitertools.compose(*fns)Composes functions right-to-left. Returns a new function.
constantlyitertools.constantly(val)Returns a function that always returns val.

Examples

Zamin
print(itertools.chain([1, 2], [3, 4], [5]));     // [1, 2, 3, 4, 5]

print(itertools.zip([1, 2, 3], ["a", "b", "c"]));
// [[1, "a"], [2, "b"], [3, "c"]]

print(itertools.enumerate(["a", "b", "c"]));
// [[0, "a"], [1, "b"], [2, "c"]]

let doubled = itertools.map(|x| x * 2, [1, 2, 3]);
print(doubled);                          // [2, 4, 6]

let evens = itertools.filter(|x| x % 2 == 0, [1, 2, 3, 4, 5]);
print(evens);                            // [2, 4]

let total = itertools.reduce(|a, b| a + b, [1, 2, 3, 4], 0);
print(total);                            // 10

print(itertools.take(3, [1, 2, 3, 4, 5]));     // [1, 2, 3]
print(itertools.drop(2, [1, 2, 3, 4, 5]));     // [3, 4, 5]
print(itertools.slice([10, 20, 30, 40, 50], 1, 4)); // [20, 30, 40]
print(itertools.unique([1, 2, 2, 3, 3, 3]));   // [1, 2, 3]
print(itertools.reverse([1, 2, 3]));            // [3, 2, 1]

print(itertools.product([1, 2], ["a", "b"]));
// [[1, "a"], [1, "b"], [2, "a"], [2, "b"]]

print(itertools.any([false, false, true]));     // true
print(itertools.all([true, true, true]));       // true

print(itertools.sorted([3, 1, 4, 1, 5]));       // [1, 1, 3, 4, 5]
print(itertools.repeat("x", 4));                // ["x", "x", "x", "x"]

let add5 = itertools.compose(
    |x| x + 5,
    |x| x * 2
);
print(add5(3));                          // 11  ((3 * 2) + 5)

let always42 = itertools.constantly(42);
print(always42("anything"));             // 42

test Module

Unit testing utilities. Run with zamin test to execute all tests in the tests/ directory.

Functions

FunctionSignatureDescription
assert_eqtest.assert_eq(expected, actual, msg?)Asserts that expected equals actual. Optional message.
assert_netest.assert_ne(expected, actual, msg?)Asserts that expected is not equal to actual.
assert_truetest.assert_true(val, msg?)Asserts that val is truthy.
assert_falsetest.assert_false(val, msg?)Asserts that val is falsy.
assert_containstest.assert_contains(container, item, msg?)Asserts that container (list, string, dict, or set) contains item.
assert_raisestest.assert_raises(fn, expected_msg?, args?)Asserts that calling fn raises an error. Optionally checks the error message.
run_testtest.run_test(name, fn)Runs a test function by name. Prints PASS or FAIL.

Examples

Zamin
func add(a, b) { return a + b; }
func divide(a, b) {
    if b == 0 { throw "division by zero"; }
    return a / b;
}

// Basic assertions
test.assert_eq(add(2, 3), 5, "addition works");
test.assert_eq(add(-1, 1), 0);
test.assert_ne(add(1, 1), 3);
test.assert_true(1 + 1 == 2);
test.assert_false(1 == 2);

// Contains
test.assert_contains([1, 2, 3], 2);
test.assert_contains("hello world", "world");
test.assert_contains({"a": 1}, "a");

// Raises
test.assert_raises(|| divide(1, 0), "division by zero");

// Named test runner
test.run_test("addition", func() {
    test.assert_eq(add(2, 3), 5);
    test.assert_eq(add(0, 0), 0);
});

time Module

Time-related functions for timestamps and delays.

Functions

FunctionSignatureDescription
nowtime.now()Returns the current time as a Unix timestamp with sub-second precision (float).
unixtime.unix()Returns the current Unix timestamp as an integer (seconds since epoch).
sleeptime.sleep(ms)Pauses execution for ms milliseconds.

Examples

Zamin
let start = time.now();
print(f"Current time: {start}");        // e.g. 1752705600.123

print(time.unix());                     // e.g. 1752705600

time.sleep(1000);                       // sleep for 1 second
print("Resumed after 1 second");

let elapsed = time.now() - start;
print(f"Elapsed: {elapsed}s");

rand Module

Random number generation and random selection.

Functions

FunctionSignatureDescription
intrand.int(min, max)Returns a random integer between min and max (inclusive).
floatrand.float()Returns a random float between 0.0 (inclusive) and 1.0 (exclusive).
choicerand.choice(list)Returns a random element from list.

Examples

Zamin
// Random integer between 1 and 100
let dice = rand.int(1, 6);
print(f"You rolled: {dice}");

// Random float [0, 1)
let r = rand.float();
print(f"Random: {r}");

// Random choice
let colors = ["red", "green", "blue"];
let pick = rand.choice(colors);
print(f"Picked: {pick}");

matrix Module

Basic matrix creation and initialization for numerical computing.

Functions

FunctionSignatureDescription
from_rowsmatrix.from_rows(rows)Creates a matrix from a list of rows (each row is a list of numbers).
zerosmatrix.zeros(rows, cols)Creates a matrix filled with zeros.
onesmatrix.ones(rows, cols)Creates a matrix filled with ones.
identitymatrix.identity(n)Creates an n x n identity matrix.
randommatrix.random(rows, cols)Creates a matrix with random values between 0.0 and 1.0.

Examples

Zamin
// Create from explicit rows
let m = matrix.from_rows([
    [1.0, 2.0, 3.0],
    [4.0, 5.0, 6.0]
]);
print(m);                               // matrix 2x3

// Zero and one matrices
let z = matrix.zeros(3, 3);             // 3x3 matrix of zeros
let o = matrix.ones(2, 4);              // 2x4 matrix of ones

// Identity matrix
let I = matrix.identity(3);             // 3x3 identity matrix
// [[1, 0, 0],
//  [0, 1, 0],
//  [0, 0, 1]]

// Random matrix
let r = matrix.random(4, 4);            // 4x4 random values
Edit this page on GitHub Last updated: July 2026