Lambda System Functions Reference

July 9, 2026 · View on GitHub

This document provides comprehensive documentation for all built-in system functions in Lambda Script.

Table of Contents

  1. Type Functions
  2. Mathematical Functions
  3. String Functions
  4. Collection Functions
  5. Date/Time Functions
  6. Variadic Argument Functions
  7. Input/Output Functions
  8. Error Handling
  9. Quick Reference Table

Type Functions

Functions for type conversion and inspection.

Type Conversion

FunctionDescriptionExampleResult
int(x)Convert to integerint("42")42
int64(x)Convert to 64-bit integerint64("9999999999")9999999999
float(x)Convert to floatfloat("3.14")3.14
decimal(x)Convert to arbitrary precision decimaldecimal("123.456")123.456n
string(x)Convert to stringstring(42)"42"
symbol(x)Convert to symbolsymbol("text")'text'
binary(x)Convert to binarybinary("hello")b'...'
number(x)Convert to number (int or float)number("3.14")3.14

Type Inspection

FunctionDescriptionExampleResult
type(x)Get type of valuetype(42)'int'
name(x)Get name of element, function, or typename(<div>)'div'
len(x)Get length of collection or stringlen([1, 2, 3])3
// Type conversion examples
int("42")          // 42
float("3.14")      // 3.14
string(42)         // "42"
symbol("text")     // 'text'

// Type inspection
type(42)           // 'int'
type("hello")      // 'string'
type([1, 2, 3])    // 'array'
name(<div>)        // 'div'
name(type(42))     // 'int'
len([1, 2, 3])     // 3
len("hello")       // 5

Mathematical Functions

Import Styles: The math module supports three import styles:

  • No import (default): math.sqrt(x), math.pi — always available
  • Global import (import math;): sqrt(x), pi — all functions available without prefix
  • Aliased import (import m:math;): m.sqrt(x), m.pi — use custom prefix

Standalone functions like abs, round, floor, ceil, trunc, sign, min, max, sum, avg are always available without any prefix or import.

Rounding & Sign (global)

These functions work on both scalars and collections (element-wise).

FunctionDescriptionScalar ExampleResultVector ExampleResult
abs(x)Absolute valueabs(-5)5abs([-1, 2, -3])[1, 2, 3]
round(x)Round to nearestround(3.7)4round([1.4, 1.6])[1, 2]
floor(x)Round downfloor(3.7)3floor([1.7, 2.3])[1, 2]
ceil(x)Round upceil(3.2)4ceil([1.2, 2.8])[2, 3]
trunc(x)Truncate toward zerotrunc(3.7)3trunc([-3.7, 3.7])[-3, 3]
sign(x)Sign (-1, 0, 1)sign(-5)-1sign([-5, 0, 3])[-1, 0, 1]

Aggregation (global)

FunctionDescriptionExampleResult
min(a, b)Minimum of two valuesmin(3, 5)3
min(vec)Minimum in collectionmin([3, 1, 2])1
max(a, b)Maximum of two valuesmax(3, 5)5
max(vec)Maximum in collectionmax([3, 1, 2])3
argmin(vec)Index of minimumargmin([5, 2, 8, 1])3
argmax(vec)Index of maximumargmax([5, 2, 8, 1])2
sum(vec)Sum of elementssum([1, 2, 3])6
avg(vec)Arithmetic meanavg([1, 2, 3])2.0
abs(-5)                 // 5
round(3.7)              // 4
floor(3.7)              // 3
ceil(3.2)               // 4
trunc(-3.7)             // -3
sign(-5)                // -1

min(3, 5)               // 3
min([3, 1, 2])          // 1
max(3, 5)               // 5
max([3, 1, 2])          // 3
argmin([5, 2, 8, 1])    // 3 (index of 1)
argmax([5, 2, 8, 1])    // 2 (index of 8)

sum([1, 2, 3, 4])       // 10
avg([1, 2, 3, 4])       // 2.5

math Module

Constants

ConstantDescriptionValue
math.piPi (π)3.1415926536
math.eEuler's number (e)2.7182818285
math.max_intLargest compact int with exact float64 round-trip9007199254740991

Compact int is bounded to ±(2532^{53} - 1). Use n literals for exact integer or decimal arithmetic beyond this compact boundary.

Trigonometric

FunctionDescriptionExampleResult
math.sin(x)Sinemath.sin([0, 1.57...])[0, 1]
math.cos(x)Cosinemath.cos([0, 1.57...])[1, 0]
math.tan(x)Tangentmath.tan([0, 0.785...])[0, 1]

Inverse Trigonometric

FunctionDescriptionExampleResult
math.asin(x)Inverse sine (arcsin)math.asin(1)1.5707963268
math.acos(x)Inverse cosine (arccos)math.acos(1)0
math.atan(x)Inverse tangent (arctan)math.atan(1)0.7853981634
math.atan2(y, x)Two-argument arctanmath.atan2(1, 1)0.7853981634

Hyperbolic

FunctionDescriptionExampleResult
math.sinh(x)Hyperbolic sinemath.sinh(1)1.1752011936
math.cosh(x)Hyperbolic cosinemath.cosh(0)1
math.tanh(x)Hyperbolic tangentmath.tanh(1)0.761594156

Inverse Hyperbolic

FunctionDescriptionExampleResult
math.asinh(x)Inverse hyperbolic sinemath.asinh(1)0.881373587
math.acosh(x)Inverse hyperbolic cosinemath.acosh(2)1.3169578969
math.atanh(x)Inverse hyperbolic tangentmath.atanh(0.5)0.5493061443

Exponential / Logarithmic

FunctionDescriptionExampleResult
math.exp(x)Exponential (e^x)math.exp([0, 1, 2])[1, e, e²]
math.exp2(x)Base-2 exponential (2^x)math.exp2(3)8
math.expm1(x)exp(x) - 1 (precise for small x)math.expm1(0)0
math.log(x)Natural logarithmmath.log([1, 2.718...])[0, 1]
math.log2(x)Base-2 logarithmmath.log2(8)3
math.log10(x)Base-10 logarithmmath.log10([1, 10, 100])[0, 1, 2]
math.log1p(x)log(1 + x) (precise for small x)math.log1p(0)0

Power / Root

FunctionDescriptionExampleResult
math.pow(b, e)Power (b^e)math.pow(2, 10)1024
math.sqrt(x)Square rootmath.sqrt([1, 4, 9])[1, 2, 3]
math.cbrt(x)Cube rootmath.cbrt(27)3
math.hypot(x, y)Hypotenuse √(x²+y²)math.hypot(3, 4)5

Statistical

FunctionDescriptionExampleResult
math.mean(vec)Alias for avgmath.mean([1, 2, 3])2.0
math.median(vec)Median valuemath.median([1, 3, 2])2
math.variance(vec)Population variancemath.variance([1, 2, 3])0.666...
math.deviation(vec)Standard deviationmath.deviation([1, 2, 3])0.816...
math.quantile(vec, p)p-th quantilemath.quantile([1,2,3,4], 0.5)2.5
math.prod(vec)Product of elementsmath.prod([2, 3, 4])24
math.cumsum(vec)Cumulative summath.cumsum([1, 2, 3])[1, 3, 6]
math.cumprod(vec)Cumulative productmath.cumprod([1, 2, 3])[1, 2, 6]
math.dot(a, b)Dot productmath.dot([1,2,3], [4,5,6])32
math.norm(vec)Euclidean normmath.norm([3, 4])5

Random

Pure functional pseudo-random number generator using the SplitMix64 algorithm. Takes an integer seed and returns a list [value, new_seed] where value is a float in [0.0, 1.0).

FunctionDescriptionExampleResult
math.random(seed)Generate random float and new seedlet x, s = math.random(42)[0.7415..., -7046...]
// math module examples
math.pi                         // 3.1415926536
math.e                          // 2.7182818285
math.sin([0, 3.14159/2])        // [0, 1]
math.cos([0, 3.14159/2])        // [1, 0]
math.asin(1)                    // 1.5707963268 (π/2)
math.atan2(1, 1)                // 0.7853981634 (π/4)
math.sinh(1)                    // 1.1752011936
math.exp2(3)                    // 8
math.log2(8)                    // 3
math.pow(2, 10)                 // 1024
math.cbrt(27)                   // 3
math.hypot(3, 4)                // 5

// statistical
math.mean([1, 2, 3, 4])         // 2.5
math.median([1, 3, 2, 4, 5])    // 3
math.variance([1, 2, 3])        // 0.666...
math.deviation([1, 2, 3])       // 0.816...
math.quantile([1, 2, 3, 4], 0.5) // 2.5
math.prod([2, 3, 4])            // 24
math.cumsum([1, 2, 3, 4])       // [1, 3, 6, 10]
math.cumprod([1, 2, 3, 4])      // [1, 2, 6, 24]
math.dot([1, 2, 3], [4, 5, 6])  // 32
math.norm([3, 4])               // 5

// random
let x, seed1 = math.random(42)
x                                // 0.7415648788 (float in [0.0, 1.0))
let x2, seed2 = math.random(seed1)
let dice = floor(x * 6) + 1     // random 1-6

String Functions

Functions for string manipulation. replace, split, and find accept either a plain string or a named string pattern as the match argument.

String Pattern Recap

String patterns are defined in the type system (see Lambda_Type.md § String Patterns) and can be used as arguments to string functions:

string digits = \d+              // one or more digits
string ws = \s+                  // one or more whitespace chars
string word = \w+                // word characters

slice(str, start, end?)

Extract a UTF-8 character slice from a string. slice(str, start, end) uses a zero-based start index inclusive and end index exclusive ([start, end)); slice(str, start) slices from start to the end. Negative indices count from the end, and out-of-range indices are clamped.

Range subscript syntax is also supported: str[a to b] returns characters a through b, inclusive. In other words, str[a to b] is equivalent to slice(str, a, b + 1).

FunctionDescriptionExampleResult
slice(str, i, j)Characters [i, j)slice("hello", 1, 4)"ell"
slice(str, i)Characters [i, end)slice("hello", 2)"llo"
str[i to j]Characters i through j, inclusive"hello"[1 to 3]"ell"
slice("hello", 0, 2)      // "he"
slice("hello", 2)         // "llo"
slice("café", 2, 4)       // "fé"  — UTF-8 character indices
"hello"[0 to 4]           // "hello"
"hello"[1 to 3]           // "ell"

replace(str, pattern_or_string, replacement)

Replace all occurrences of a pattern or substring in a string. Returns a new string.

FunctionDescriptionExampleResult
replace(str, pattern, repl)Replace all pattern matchesreplace("a1b2", \d, "X")"aXbX"
replace(str, string, repl)Replace all substring matchesreplace("abc", "b", "X")"aXc"
string digit = \d
string digits = \d+
string ws = \s+

replace("a1b2c3", digit, "X")         // "aXbXcX"
replace("a1b22c333", digits, "N")     // "aNbNcN"
replace("hello   world", ws, " ")     // "hello world"
replace("no-digits", digit, "X")      // "no-digits" (no match → unchanged)
replace("a1b2", digit, "")            // "ab" (delete matches)
replace("abc", "b", "")               // "ac" (plain string delete)

split(str, pattern_or_string, keep_delimiters?)

Split a string by pattern or substring. Returns an array of substrings.

FunctionDescriptionExampleResult
split(str, pattern)Split by patternsplit("a1b2", \d)["a", "b", ""]
split(str, string)Split by substringsplit("a,b,c", ",")["a", "b", "c"]
split(str, sep, true)Split, keep delimiterssplit("a1b2", \d, true)["a","1","b","2",""]
string digit = \d
string digits = \d+
string ws = \s+

split("a1b2c3", digit)                // ["a", "b", "c", ""]
split("hello   world", ws)            // ["hello", "world"]
split("a1b22c333", digits)            // ["a", "b", "c", ""]
split("no-match", digit)              // ["no-match"]
split("a1b2c3", digit, true)          // ["a", "1", "b", "2", "c", "3", ""]  — keep delimiters
split("a,b,c", ",", true)             // ["a", ",", "b", ",", "c"]           — works with strings too

join(strs, separator)

Join a list of strings with a separator. Returns a string.

FunctionDescriptionExampleResult
join(strs, sep)Join with separatorjoin(["a", "b", "c"], ", ")"a, b, c"
join(strs, "")Concatenatejoin(["hello", "world"], "")"helloworld"
join(["a", "b", "c"], ", ")           // "a, b, c"
join(["hello"], ", ")                 // "hello"
join(["x", "y"], "-")                // "x-y"

find(str, pattern_or_string)

Find all occurrences of a pattern or substring. Returns a list of match maps {value, index}.

FunctionDescriptionExampleResult
find(str, pattern)Find all pattern matchesfind("a1b22", \d+)[{value:"1",index:1}, ...]
find(str, string)Find all substring matchesfind("abab", "ab")[{value:"ab",index:0}, ...]

Each match is a map with:

  • value — the matched substring
  • index — the start position (0-based) in the source string
string digits = \d+
string words = \w+

find("a1b22c333", digits)
// [{value: "1", index: 1}, {value: "22", index: 3}, {value: "333", index: 6}]

find("hello world", words)
// [{value: "hello", index: 0}, {value: "world", index: 6}]

find("hello world hello", "lo")
// [{value: "lo", index: 3}, {value: "lo", index: 14}]

find("no-match", digits)
// [] (empty array)

// Extract just matching values via pipe
find("a1b22", digits) | ~.value     // ["1", "22"]

contains(str, substring)

Check if a string contains a substring. Returns true or false. Also works on collections (see Collection Functions).

FunctionDescriptionExampleResult
contains(str, sub)Check substring presencecontains("hello", "ell")true
contains("hello world", "world")   // true
contains("hello world", "xyz")     // false
contains("abcdef", "cd")           // true
contains("", "a")                  // false

starts_with(str, prefix)

Check if a string starts with a given prefix. Returns true or false.

FunctionDescriptionExampleResult
starts_with(str, prefix)Check prefixstarts_with("hello", "hel")true
starts_with("hello world", "hello")   // true
starts_with("hello world", "world")   // false
starts_with("abc", "")                // true
starts_with("abc", "abcd")            // false

ends_with(str, suffix)

Check if a string ends with a given suffix. Returns true or false.

FunctionDescriptionExampleResult
ends_with(str, suffix)Check suffixends_with("hello", "llo")true
ends_with("hello world", "world")   // true
ends_with("hello world", "hello")   // false
ends_with("abc", "")                // true
ends_with("abc", "abcd")            // false

index_of(str, substring)

Return the index of the first occurrence of a substring (-1 if not found). Also works on collections (see Collection Functions).

FunctionDescriptionExampleResult
index_of(str, sub)First occurrence indexindex_of("hello", "ll")2
index_of("hello world", "world")   // 6
index_of("hello world", "xyz")     // -1
index_of("abcabc", "bc")           // 1

last_index_of(str, substring)

Return the index of the last occurrence of a substring (-1 if not found). Also works on collections (see Collection Functions).

FunctionDescriptionExampleResult
last_index_of(str, sub)Last occurrence indexlast_index_of("abcabc", "bc")4
last_index_of("abcabc", "abc")    // 3
last_index_of("hello", "l")       // 3
last_index_of("hello", "xyz")     // -1

trim(str) / trim_start(str) / trim_end(str)

Remove whitespace from a string.

FunctionDescriptionExampleResult
trim(str)Remove leading and trailing whitespacetrim(" hello ")"hello"
trim_start(str)Remove leading whitespacetrim_start(" hello ")"hello "
trim_end(str)Remove trailing whitespacetrim_end(" hello ")" hello"
trim("  hello world  ")       // "hello world"
trim_start("  hello  ")       // "hello  "
trim_end("  hello  ")         // "  hello"
trim("\t\n hello \n")         // "hello"

upper(str) / lower(str)

Convert string case. Unicode-aware.

FunctionDescriptionExampleResult
upper(str)Convert to uppercaseupper("hello")"HELLO"
lower(str)Convert to lowercaselower("HELLO")"hello"
upper("hello")         // "HELLO"
lower("HELLO")         // "hello"
upper("café")          // "CAFÉ"
lower("Straße")        // "straße"

normalize(str)

Normalize a string (Unicode normalization).

url_resolve(base, relative)

Resolve a relative URL against a base URL.

url_resolve("https://example.com/a/b", "../c")    // "https://example.com/c"
url_resolve("https://example.com/a/", "page.html") // "https://example.com/a/page.html"

ord(str)

Return the Unicode code point (int) of the first character. Works on both strings and symbols.

ord("A")             // 65
ord("é")             // 233
ord("😀")            // 128512
ord('A')             // 65 (symbol input)
ord("hello")         // 104 (first character 'h')
ord("")              // 0 (empty string has no first character)

chr(int)

Return a 1-character string from a Unicode code point.

chr(65)              // "A"
chr(233)             // "é"
chr(128512)          // "😀"
chr(-1)              // null (out of range)

Round-trip:

chr(ord("Z"))        // "Z"
ord(chr(65))         // 65

Collection Functions

Functions for working with arrays and other collections.

Query & Test

FunctionDescriptionExampleResult
len(x)Length of collectionlen([1, 2, 3])3
contains(vec, val)Check if element existscontains([1, 2, 3], 2)true
index_of(vec, val)Index of first match (-1 if none)index_of([1, 2, 3], 2)1
last_index_of(vec, val)Index of last match (-1 if none)last_index_of([1, 2, 1], 1)2
all(vec)All elements truthy?all([true, true, false])false
any(vec)Any element truthy?any([false, false, true])true

contains, index_of, and last_index_of work on lists, typed arrays (int, float), maps (key existence), and elements (children). They also work on strings (see String Functions).

// List membership
contains([1, 2, 3], 2)              // true
contains(["a", "b", "c"], "d")      // false

// Index search
index_of([10, 20, 30, 20], 20)      // 1
last_index_of([10, 20, 30, 20], 20) // 3
index_of([1, 2, 3], 99)             // -1

// Map key existence
contains({name: "Alice", age: 30}, 'name')   // true
contains({x: 1, y: 2}, 'z')                  // false

Extraction

FunctionDescriptionExampleResult
slice(vec, i, j)Extract slice [i, j)slice([1,2,3,4], 1, 3)[2, 3]
slice(vec, i)Extract slice [i, end)slice([1,2,3,4], 2)[3, 4]
take(vec, n)First n elementstake([1, 2, 3], 2)[1, 2]
drop(vec, n)Drop first n elementsdrop([1, 2, 3], 1)[2, 3]

Transformation

FunctionDescriptionExampleResult
reverse(vec)Reverse orderreverse([1, 2, 3])[3, 2, 1]
sort(vec)Sort ascendingsort([3, 1, 2])[1, 2, 3]
sort(vec, 'desc')Sort descendingsort([1, 2, 3], 'desc')[3, 2, 1]
sort(vec, fn)Sort by key functionsort(users, ~.age)Sorted by age
sort(vec, options)Sort with options mapsort(users, {dir: 'desc', by: ~.age})Sorted by age desc
unique(vec)Remove duplicates (preserves order)unique([1, 2, 2, 3])[1, 2, 3]
set(vec)Remove duplicatesset([1, 1, 2, 2, 3])[1, 2, 3]
zip(v1, v2)Pair elementszip([1, 2], [3, 4])[(1, 3), (2, 4)]

Construction

FunctionDescriptionExampleResult
fill(n, value)Vector of n copiesfill(3, 5)[5, 5, 5]
range(start, end, step)Range with steprange(0, 10, 2)[0, 2, 4, 6, 8]

Reduction

FunctionDescriptionExampleResult
reduce(vec, fn)Reduce with binary functionreduce([1,2,3], (a,b) => a+b)6

Reduce a collection to a single value by applying a binary function cumulatively. Uses the first element as the initial accumulator.

slice([1, 2, 3, 4], 1, 3)  // [2, 3]
slice([1, 2, 3, 4], 2)     // [3, 4]
take([1, 2, 3, 4], 2)      // [1, 2]
drop([1, 2, 3, 4], 2)      // [3, 4]

all([true, true, false])   // false
any([false, false, true])  // true

reverse([1, 2, 3])         // [3, 2, 1]
sort([3, 1, 2])            // [1, 2, 3]
sort([1, 2, 3], 'desc')     // [3, 2, 1]

// Sort by key function
let users = [{name: "Bob", age: 30}, {name: "Alice", age: 25}]
sort(users, ~.age)         // sorted by age ascending
sort(users, {dir: 'desc', by: ~.age})   // sorted by age descending

unique([1, 2, 2, 3, 3])    // [1, 2, 3]
zip([1, 2], ["a", "b"])    // [(1, "a"), (2, "b")]

fill(3, 0)                 // [0, 0, 0]
range(0, 10, 2)            // [0, 2, 4, 6, 8]

reduce([1, 2, 3, 4], (a, b) => a + b)     // 10 (sum)
reduce([1, 2, 3, 4, 5], (a, b) => a * b)  // 120 (product)

Note: reduce requires at least one element. If only one element, it is returned directly without calling the function.


Date/Time Functions

Functions for date and time operations.

Current Time

FunctionDescriptionExampleResult
datetime()Current date and timedatetime()t'2025-01-23T14:30:00'
datetime(x)Parse as datetimedatetime("2025-01-01")t'2025-01-01'
today()Current datetoday()t'2025-01-23'
now()Current timestamp (proc)now()t'2025-01-23T14:30:00'
justnow()Time when current script evaluation startedjustnow()t'14:30:00'

Date/Time Extraction

FunctionDescriptionExampleResult
date(dt)Extract date partdate(t'2025-01-01T14:30')t'2025-01-01'
time(dt)Extract time parttime(t'2025-01-01T14:30')t'14:30:00'
datetime()                 // Current date and time
today()                    // Current date
justnow()                  // Current time

date(t'2025-01-01T14:30')  // t'2025-01-01'
time(t'2025-01-01T14:30')  // t'14:30:00'

Variadic Argument Functions

Functions for accessing variable arguments inside variadic functions.

FunctionDescriptionExampleResult
varg()All variadic argumentsvarg()List of args
varg(n)nth variadic argument (0-indexed)varg(0)First arg
// Define a variadic function
fn sum_all(...) => sum(varg())
fn first_arg(...) => varg(0)
fn count_args(...) => len(varg())

// Use the functions
sum_all(1, 2, 3, 4)        // 10
first_arg("a", "b", "c")   // "a"
count_args(1, 2, 3)        // 3

Input/Output Functions

Lambda Script provides comprehensive support for file I/O with unified path/URL handling and multiple document formats.

Unified Path and URL Handling

Lambda uses Path literals with unified syntax for both local files and remote URLs:

// Local paths
let local = /.data.'config.json'         // Relative path
let absolute = /Users.name.project       // Absolute path

// Remote URLs
let api = https.'api.example.com'.data   // HTTPS URL
let file_url = /path.to.file             // File URL

// All work uniformly with I/O functions
let data = input(local)
let remote = input(api)

Pure I/O Functions

These functions can be used anywhere (in both fn and pn functions).

input(target) / input(target, format)

Parse content from a file path or URL.

FunctionDescriptionExample
input(target)Parse target (auto-detect format)input(/.'data.json')
input(target, format)Parse target with specified formatinput("data.json", 'json')

Supported Input Formats: json, xml, html, yaml, toml, markdown, csv, latex, rtf, pdf, css, ini, math

FormatDescriptionExample
JSONJavaScript Object Notationinput(/.'data.json', 'json')
XMLExtensible Markup Languageinput(/.'config.xml', 'xml')
HTMLHyperText Markup Languageinput(/.'page.html', 'html')
YAMLYAML Ain't Markup Languageinput(/.'config.yaml', 'yaml')
TOMLTom's Obvious Minimal Languageinput(/.'config.toml', 'toml')
MarkdownMarkdown markupinput(/.'doc.md', 'markdown')
CSVComma-Separated Valuesinput(/.'data.csv', 'csv')
LaTeXLaTeX markupinput(/.'doc.tex', 'latex')
RTFRich Text Formatinput(/.'doc.rtf', 'rtf')
PDFPortable Document Formatinput(/.'doc.pdf', 'pdf')
CSSCascading Style Sheetsinput(/.'style.css', 'css')
INIConfiguration filesinput(/.'config.ini', 'ini')
MathMathematical expressionsinput(/.'formula.txt', 'math')

Input Function Usage:

// Basic input parsing with Path literals
let data = input(/.'file.json', 'json')
let config = input(/.'settings.yaml', 'yaml')

// Input from URLs
let api_data = input(https.'api.example.com'.'users.json')

// Input with options map
let math_expr = input(/.'formula.txt', {type: 'math', flavor: 'latex'})
let csv_data = input(/.'data.csv', {type: 'csv', delimiter: ','})

// Auto-detection (based on file extension)
let auto_data = input(/.'document.md')  // Automatically detects Markdown

parse(str) / parse(str, format)

Parse a string into Lambda data structures. Like input() but operates on string content instead of file paths/URLs.

FunctionDescriptionExample
parse(str)Parse string (auto-detect format)parse("{\"x\": 1}")
parse(str, format)Parse string with specified formatparse(str, 'json')

Supported Formats: Same as input()json, xml, html, yaml, toml, markdown, csv, latex, css, ini, math

// Parse JSON string
let data^err = parse("{\"name\": \"Alice\", \"age\": 30}", 'json')
data.name     // "Alice"

// Auto-detect JSON from content
let data2^err = parse("{\"x\": 1}")
data2.x       // 1

// Parse with options map
let expr^err = parse("x^2 + y", {type: 'math', flavor: 'latex'})

// Parse CSV from string
let csv^err = parse("name,age\nAlice,30\nBob,25", 'csv')

Note: parse() can raise errors. Use let result^err = parse(...) for error-safe handling.

exists(target)

Check if a file, directory, or URL target exists. Returns true or false.

let file_exists = exists(/.'config.json')
let dir_exists = exists(/.data)

if exists(/.'cache.json') {
    let cached = input(/.'cache.json')
}

format(data) / format(data, type)

Format data as a string in various formats. This is a pure function that returns a string.

FunctionDescriptionExample
format(data)Format data as Lambda representationformat(obj)
format(data, type)Format data as specified typeformat(obj, 'json')
// Format data as different types
let json_str = format(data, 'json')
let yaml_str = format(data, 'yaml')
let xml_str = format(data, 'xml')

// Format with options
let pretty_json = format(data, {type: 'json', indent: 2})
let compact_json = format(data, {type: 'json', compact: true})

Procedural I/O Functions

Functions that have side effects (I/O, state changes). These are only available in procedural functions (pn).

Overview

FunctionDescriptionExample
print(args...)Print values to consoleprint("x =", x)
output(data, target)Write data to file/URLoutput(data, /.'out.json')
output(data, target, {mode: "append"})Append data to file/URLoutput(line, /.'log.txt', {mode: "append"})
io.copy(src, dst)Copy file or directoryio.copy(/.'a.txt', /.'b.txt')
io.move(src, dst)Move/rename file or directoryio.move(/.old, /.new)
io.delete(target)Delete file or directoryio.delete(/.'temp.txt')
io.mkdir(path)Create directoryio.mkdir(/.data)
io.touch(path)Create empty file or update timestampio.touch(/.'flag.txt')
io.symlink(target, link)Create symbolic linkio.symlink(/.src, /.link)
io.chmod(path, mode)Change file permissionsio.chmod(/.'script.sh', "755")
io.rename(src, dst)Rename file or directoryio.rename(/.'a.txt', /.'b.txt')
io.fetch(url, options)HTTP fetch with optionsio.fetch(https.'api.example.com', {method: 'POST'})
cmd(command, args...)Execute shell commandcmd("ls", "-la")
clock()Monotonic clock in secondsclock()

print(args...)

Prints values to the console (stdout). Arguments are stringified and joined with a single space separator.

print("Hello, world!")
print(42)
print([1, 2, 3])
print("x =", 42)

output(data, target) / output(data, target, format)

Writes data to a file or URL. The format can be auto-detected from the target extension or explicitly specified.

pn save_data() {
    let data = {name: "Alice", age: 30, scores: [95, 87, 92]}

    // Using Path literals
    output(data, /.'result.json')     // Writes JSON
    output(data, /.'result.yaml')     // Writes YAML
    output(data, /.'result.xml')      // Writes XML

    // Explicit format specification
    output(data, /.'data.txt', 'json')    // Force JSON format
    output(data, /.'data.out', 'yaml')    // Force YAML format

    // With options
    output(data, /.'pretty.json', {type: 'json', indent: 4})
}

Supported output formats:

FormatExtensionDescription
json.jsonJSON format
yaml.yaml, .ymlYAML format
xml.xmlXML format
html.html, .htmHTML format
markdown.mdMarkdown format
text.txtPlain text
toml.tomlTOML format
ini.iniINI configuration format

Output Function

Lambda uses output(...) for file writing in procedural functions.

Write/Truncate

output(data, target) writes data to a target, truncating existing content:

pn generate_report() {
    let report = {title: "Monthly Report", date: today(), items: [...]}
    output(report, /.reports.'monthly.json')
}
Append

Pass {mode: "append"} as the third argument to append:

pn log_event(event) {
    let entry = format({time: now(), event: event}, 'json')
    output(entry, /.logs.'events.jsonl', {mode: "append"})
}

pn process_items(items) {
    for item in items {
        output(process(item), /.'output.txt', {mode: "append"})
    }
}

io Module Functions

The io module provides procedural functions for file system operations.

Import Styles: The io module supports three import styles:

  • No import (default): io.copy(/.a, /.b) — always available
  • Global import (import io;): copy(/.a, /.b) — all functions without prefix
  • Aliased import (import f:io;): f.copy(/.a, /.b) — use custom prefix
io.copy(source, destination)

Copy a file or directory to a new location.

pn backup_config() {
    io.copy(/.'config.json', /.backup.'config.json')
    io.copy(/.data, /.backup.data)  // Copy directory recursively
}
io.move(source, destination)

Move or rename a file or directory.

pn archive_logs() {
    io.move(/.logs.'current.log', /.logs.archive.'2024-01.log')
}
io.delete(target)

Delete a file or directory.

pn cleanup() {
    io.delete(/.'temp.txt')
    io.delete(/.cache)  // Delete directory recursively
}
io.mkdir(path)

Create a directory (and parent directories if needed).

pn setup_project() {
    io.mkdir(/.src)
    io.mkdir(/.tests)
    io.mkdir(/.docs.api)  // Creates parent dirs too
}
io.touch(path)

Create an empty file or update its modification timestamp.

pn mark_complete() {
    io.touch(/.build.'.done')
}

Create a symbolic link.

pn setup_links() {
    io.symlink(/.config.'production.json', /.'config.json')
}
io.chmod(path, mode)

Change file permissions (Unix-style).

pn make_executable() {
    io.chmod(/.scripts.'deploy.sh', "755")
    io.chmod(/.'secrets.env', "600")
}
io.rename(source, destination)

Rename a file or directory (alias for move within same directory).

pn rename_file() {
    io.rename(/.'draft.txt', /.'final.txt')
}
io.fetch(url, options)

Perform HTTP requests with full control over method, headers, and body.

pn api_operations() {
    // GET request
    let data = io.fetch(https.'api.example.com'.users, {
        method: 'GET',
        headers: {Authorization: "Bearer token123"}
    })

    // POST request
    let result = io.fetch(https.'api.example.com'.users, {
        method: 'POST',
        headers: {Content-Type: "application/json"},
        body: format({name: "Alice", email: "alice@example.com"}, 'json')
    })
}

cmd(command, args...)

Execute a shell command and return the result.

pn run_commands() {
    let files = cmd("ls", "-la")
    let date = cmd("date", "+%Y-%m-%d")

    // With multiple arguments
    cmd("git", "commit", "-m", "Update files")
}

clock()

Returns the current value of a monotonic clock as a float in seconds. Useful for measuring elapsed time in benchmarks and performance profiling. The returned value has nanosecond precision and is not related to wall-clock time.

pn benchmark() {
    var t0 = clock()
    // ... work to measure ...
    var t1 = clock()
    var elapsed_ms = (t1 - t0) * 1000.0
    print("Elapsed: " + string(elapsed_ms) + " ms")
}

Error Handling

Functions for creating and handling errors.

FunctionDescriptionExampleResult
error(msg)Create error valueerror("Invalid input")Error
// Create an error
error("Something went wrong")

// Error handling in expressions
let result = if (x == 0) error("Division by zero") else (y / x)

// Check for error
if (result is error) {
    print("Error occurred")
}

Quick Reference Table

Type Functions

FunctionArgsDescription
len1Get length
type1Get type
int1Convert to int
int641Convert to int64
float1Convert to float
decimal1Convert to decimal
string1Convert to string
symbol1Convert to symbol
binary1Convert to binary
number1Convert to number

Math Functions

FunctionArgsDescription
abs1Absolute value
round1Round to nearest
floor1Round down
ceil1Round up
sign1Sign (-1, 0, 1)
trunc1Truncate toward zero
math.sqrt1Square root
math.cbrt1Cube root
math.hypot2Hypotenuse √(x²+y²)
math.pow2Power (b^e)
math.log1Natural log
math.log21Base-2 log
math.log101Base-10 log
math.log1p1log(1 + x)
math.exp1Exponential (e^x)
math.exp21Base-2 exponential
math.expm11exp(x) - 1
math.sin1Sine
math.cos1Cosine
math.tan1Tangent
math.asin1Inverse sine
math.acos1Inverse cosine
math.atan1Inverse tangent
math.atan22Two-arg arctan
math.sinh1Hyperbolic sine
math.cosh1Hyperbolic cosine
math.tanh1Hyperbolic tangent
math.asinh1Inverse hyp. sine
math.acosh1Inverse hyp. cosine
math.atanh1Inverse hyp. tangent
math.pi-Pi (π) constant
math.e-Euler's number constant
math.max_int-Maximum compact int constant

Aggregation Functions (Global)

FunctionArgsDescription
min1-2Minimum
max1-2Maximum
argmin1Index of min
argmax1Index of max
sum1Sum
avg1Average

Statistical Functions (math Module)

FunctionArgsDescription
math.mean1Mean
math.median1Median
math.variance1Variance
math.deviation1Std deviation
math.quantile2Quantile
math.prod1Product
math.cumsum1Cumulative sum
math.cumprod1Cumulative product
math.dot2Dot product
math.norm1Euclidean norm
math.random0-2Random number

String Functions

FunctionArgsDescription
contains2Check if string contains substring
starts_with2Check if string starts with prefix
ends_with2Check if string ends with suffix
index_of2Index of first substring occurrence
last_index_of2Index of last substring occurrence
trim1Remove leading/trailing whitespace
trim_start1Remove leading whitespace
trim_end1Remove trailing whitespace
upper1Convert to uppercase
lower1Convert to lowercase
replace3Replace pattern/substring in string
split2-3Split string by pattern/substring
join2Join list of strings with separator
find2Find all pattern/substring matches
ord1Unicode code point of first character
chr1Character from Unicode code point
normalize1Normalize string
url_resolve2Resolve relative URL against base

Collection Functions

FunctionArgsDescription
contains2Check element membership
index_of2Index of first matching element
last_index_of2Index of last matching element
slice2 or 3Extract slice; 2-arg form slices to end
set1+Remove duplicates
all1All truthy
any1Any truthy
reverse1Reverse order
sort1-2Sort (dir, key fn, or options map)
unique1Unique elements
take2Take first n
drop2Drop first n
zip2Zip vectors
fill2Fill vector
range3Range with step
reduce2Reduce with binary fn

Date/Time Functions

FunctionArgsDescription
datetime0-1Date and time
date1Extract date
time1Extract time
today0Current date (proc)
now0Current time (proc)
justnow0Time only

I/O Functions (Pure)

FunctionArgsDescription
input1-2Parse file/URL
parse1-2Parse string content
exists1Check if target exists
format1-2Format data as string

I/O Functions (Procedural)

FunctionArgsDescription
print0+Print values to console
output2-3Write to file/URL
io.copy2Copy file/directory
io.move2Move file/directory
io.delete1Delete file/directory
io.mkdir1Create directory
io.touch1Create/update file
io.symlink2Create symbolic link
io.chmod2Change permissions
io.rename2Rename file/directory
io.fetch2HTTP request
cmd1+Shell command
clock0Monotonic clock (seconds)

Other Functions

FunctionArgsDescription
error1Create error
varg0-1Variadic args