Standard Library

Built-in functions are available everywhere by bare name. Grouped functionality lives in seventeen modules called with dot syntax, none of which need an import. Modules that touch the outside world are denied by default and enabled per run with capability flags.

Built-in functions

Output and input

FunctionDescription
print(values...)Print any number of values, space separated, with a trailing newline.
fmt(template, args...)Replace each {} with the next argument. Placeholder and argument counts must match, else ValueError.
input(), input(prompt)Read one line from standard input, newline stripped.

Conversion and inspection

FunctionDescription
num(text)Parse text to an integer when exact, a float otherwise; ConversionError on failure.
str(v)Render any value as text.
type(v)The kind of a value: val, seq, map, pair, flow, func, class, instance, or null.
len(v), count(v)Length of a seq, text (in characters), map, or finite flow. The two names are interchangeable.

Numbers

FunctionDescription
abs(x)Absolute value, preserving int or float.
floor(x), ceil(x)Round down or up, returning an integer.
round(x)Round to the nearest integer; exact halves go to the even neighbor, so round(2.5) is 2 and round(3.5) is 4.
clamp(x, lo, hi)Constrain x to the closed range.
pow(a, b)Same semantics as the ** operator.
sqrt(x)Square root; negative input raises ValueError.
min(a, b), max(a, b)Smaller or larger of two values.
min(seq), max(seq), sum(seq)Reduce a non-empty seq (or a range) to one value. Large sums parallelize automatically in native builds.

The trigonometric and exponential family is also available by bare name: sin, cos, tan, asin, acos, atan, sinh, cosh, tanh, exp, ln, log (natural), log2, log10, and cbrt. Each takes one number and returns a float.

Sequences

FunctionDescription
make_seq(n, init)A new seq of length n, every element init.
push(s, x)Append in place; returns null.
collect(flow)Materialize a finite flow into a seq. Consuming an infinite flow raises InfiniteFlowError; bound it with a loop's until clause instead.
slice(s, i, j)Elements from i up to but not including j; works on text too.
take(s, n)The first n elements. (There is no drop counterpart in 0.1.0; use slice(s, n, len(s)).)
sort(s)Sorted copy, numeric or lexicographic.
sort_by(s, cmp)Sorted copy using cmp(a, b), negative when a comes first.
reverse(s)Reversed copy of a seq or text.
unique(s)Distinct elements, first occurrence order.
flatten(s)Concatenate one level of nested seqs.
zip(a, b)Seq of pairs, as long as the shorter input.
enumerate(s)Seq of (index, element) pairs.
contains(coll, x)Membership in a seq, or substring in text.
join(s, sep)Concatenate elements into text with a separator.

Higher-order

FunctionDescription
map(s, f)Apply f to each element; new seq.
filter(s, pred)Keep elements where pred is truthy.
reduce(s, init, f)Left fold: accumulate f(acc, x) starting from init.

The >> and ? operators are often the lighter spelling of map and filter; see Operators.

Text

upper, lower, trim, split, and join are builtins; the richer text module is documented with examples in the Text chapter.

Testing

FunctionDescription
assert_eq(a, b)Raise RuntimeError reporting both values unless a == b.

Modules

Modules are called with dot syntax: math.gcd(12, 18), json.parse(s). The fs, proc, and http modules touch the machine and are gated by the capability flags described in Command Line.

math

Everything from the bare-name math functions plus:

FunctionDescription
math.gcd(a, b), math.lcm(a, b)Greatest common divisor, least common multiple.
math.factorial(n)Integer factorial.
math.atan2(y, x)Two-argument arctangent.
math.log_n(x, base)Logarithm in an arbitrary base.
math.torad(deg), math.todeg(rad)Angle conversions.
math.trunc(x)Drop the fractional part.
math.sign(x)Negative one, zero, or one.
math.is_finite(x), math.is_nan(x)Float classification.

stats

FunctionDescription
stats.avg(s)Arithmetic mean.
stats.median(s)Middle value.
stats.mode(s)Most frequent value.
stats.range(s)Max minus min.
stats.sum, stats.count, stats.min, stats.maxThe reductions, namespaced.

text

String operations beyond the builtins: search, replace, padding, character and byte access, parsing, and content tests. Fully documented in the Text chapter.

regex

FunctionDescription
regex.match(pat, s)Whether the pattern matches anywhere; bool.
regex.find(pat, s)First match as a map with start, end, and text, or null.
regex.find_all(pat, s)Every match, as a seq of those maps.
regex.replace(pat, s, with), regex.replace_all(pat, s, with)Replace the first, or every, match.
regex.split(pat, s)Split on matches.
regex.groups(pat, s)Capture groups of the first match, or null.
line = "error at 14:22 in parse"
m = regex.find("[0-9]+:[0-9]+", line)
print(m.text)     # 14:22
print(m.start)    # 9

json

FunctionDescription
json.parse(text)JSON text to J2 values: objects become maps, arrays become seqs.
json.stringify(v)Compact JSON text.
json.stringify_pretty(v)Indented JSON text.
config = json.parse("{\"retries\": 3, \"verbose\": true}")
print(config.retries)                    # 3
print(json.stringify([1, 2, 3]))         # [1,2,3]

time

A monotonic timer for measuring work:

t = time.now()
total := 0
for i in 1..100000 { total += i }
print(fmt("sum={} in {} ms", total, time.elapsed_ms(t)))
FunctionDescription
time.now()An opaque token for the current instant.
time.elapsed_ms(t)Milliseconds since the token, as a float.

date

Calendar time. Date values are maps carrying year, month, day, hour, minute, second, weekday, iso, epoch_secs, and epoch_millis.

FunctionDescription
date.now(), date.now_utc()The current date-time, local or UTC.
date.from_epoch(secs)Build a date from a Unix timestamp.
date.format(d, fmt)Render with a strftime-style format.
date.parse(s, fmt)Parse text against a format.
date.add_seconds(d, n), date.add_days(d, n)Shifted copies.
date.diff_seconds(a, b)Difference between two dates.

rand

A fast deterministic generator: seed it and the stream is reproducible, which the test suite and the benchmark programs rely on.

FunctionDescription
rand.seed(n)Set the generator state.
rand.next_int()A random integer.
rand.next_float()A float in [0, 1).
rand.next_range(lo, hi)An integer in [lo, hi).

hash

FunctionDescription
hash.sha256(x), hash.sha512(x), hash.md5(x)Digest of text or a byte seq, as lowercase hex text.
hash.xxhash(x)Fast non-cryptographic hash, as an integer.

base64 and hex

FunctionDescription
base64.encode(x), base64.decode(t)Standard alphabet; decode returns a byte seq.
base64.encode_url(x), base64.decode_url(t)URL-safe alphabet.
hex.encode(x), hex.decode(t)Hexadecimal text and back.

bits

Bit manipulation as functions, including the right shift the operator set leaves out:

FunctionDescription
bits.band, bits.bor, bits.bxor, bits.bnotThe bitwise operators, as functions.
bits.shl(a, n), bits.shr(a, n)Shifts.
bits.popcount(a)Number of set bits.
bits.leading_zeros(a), bits.trailing_zeros(a)Zero runs at either end.

sys

FunctionDescription
sys.os(), sys.arch()Operating system and architecture names.
sys.hostname(), sys.username()Machine and user names.
sys.cpu_count()Logical CPU count, the number the parallel runtime works with.

fs (requires --allow-fs)

FunctionDescription
fs.read_file(p), fs.write_file(p, t), fs.append_file(p, t)Whole-file text I/O.
fs.read_lines(p)A seq of lines.
fs.read_bytes(p), fs.write_bytes(p, b)Byte seqs in and out.
fs.exists(p), fs.is_file(p), fs.is_dir(p)Path tests.
fs.list_dir(p)Names in a directory.
fs.mkdir(p), fs.mkdir_p(p)Create a directory, or a whole path.
fs.copy(a, b), fs.rename(a, b)Copy and move.
fs.remove(p), fs.remove_dir(p)Delete a file or directory.
fs.metadata(p)A map with size, is_file, is_dir, modified_epoch.
# j2 --allow-fs sum_column.j2 data.csv
lines = fs.read_lines("data.csv")
total := 0.0
for l in lines {
    fields = split(l, ",")
    try { total += num(trim(fields[0])) }
    else ConversionError { }
}
print(total)

proc (proc.run requires --allow-proc)

FunctionDescription
proc.argv()Program arguments; element 0 is the program itself.
proc.env(name)An environment variable, or null.
proc.set_env(name, v)Set an environment variable for this process.
proc.cwd(), proc.chdir(p)Working directory.
proc.exit(code)End the program with a status.
proc.run(cmd, args)Run a program; returns a map with stdout, stderr, status. Gated.

http (requires --allow-net)

FunctionDescription
http.get(url)GET; returns a map with status, body, headers.
http.post(url, body)POST with a text body.
http.post_json(url, v)POST a value serialized as JSON.

Requests to loopback and private-network addresses are refused even under --allow-net, as a guard against request-forgery tricks; set J2_ALLOW_LOCAL_NET=1 when a script legitimately talks to localhost.

# j2 --allow-net fetch.j2
r = http.get("https://example.com")
print(r.status)
print(len(r.body))

async

Explicit concurrency helpers for I/O-shaped work. For compute, prefer plain code and the automatic parallelizer.

FunctionDescription
async.parallel(fns)Run a seq of zero-argument functions concurrently; returns their results in order.
async.sleep_ms(n)Pause.
async.http_get(url)Concurrent GET (gated like http).
async.read_file(p), async.write_file(p, t)Concurrent file I/O (gated like fs).
results = async.parallel([
    func() = 6 * 7,
    func() = 6 + 7
])
print(results)    # [42,13]