Skip to main content

Built-in Functions & Decorators

Math Functions

Basic Math

FunctionDescriptionExample
sqrt(x)Square rootsqrt(16)4
abs(x)Absolute valueabs(-5)5
floor(x)Round downfloor(3.7)3
ceil(x)Round upceil(3.2)4
round(x)Round to nearestround(3.5)4
trunc(x)Truncate decimaltrunc(3.9)3
sign(x)Sign of numbersign(-5)-1
min(a, b, ...)Minimum valuemin(3, 7, 1)1
max(a, b, ...)Maximum valuemax(3, 7, 1)7
clamp(x, min, max)Clamp to rangeclamp(15, 0, 10)10
lerp(a, b, t)Linear interpolationlerp(0, 10, 0.5)5

Powers & Logarithms

FunctionDescriptionExample
pow(base, exp)Powerpow(2, 3)8
exp(x)e^xexp(1)2.718...
log(x)Natural loglog(E())1
log(x, base)Log with baselog(8, 2)3
log10(x)Log base 10log10(100)2
log2(x)Log base 2log2(8)3

Trigonometry

FunctionDescriptionExample
sin(x)Sine (radians)sin(PI() / 2)1
cos(x)Cosine (radians)cos(0)1
tan(x)Tangent (radians)tan(0)0
asin(x)Arc sineasin(1)1.57...
acos(x)Arc cosineacos(1)0
atan(x)Arc tangentatan(1)0.785...
atan2(y, x)Arc tangent of y/xatan2(1, 1)0.785...
sinh(x)Hyperbolic sinesinh(0)0
cosh(x)Hyperbolic cosinecosh(0)1
tanh(x)Hyperbolic tangenttanh(0)0

Constants

FunctionDescriptionValue
PI()Pi constant3.14159...
E()Euler's number2.71828...
TAU()Tau (2*PI)6.28318...
INFINITY()Positive infinityInfinity

Random Functions

FunctionDescriptionExample
random()Random float in [0, 1)random()0.742...
randomInt(max)Random int in [0, max)randomInt(10)7
randomInt(min, max)Random int in [min, max)randomInt(5, 10)8
randomFloat(max)Random float in [0, max)randomFloat(10)7.3...
randomFloat(min, max)Random float in [min, max)randomFloat(5, 10)8.2...
randomChoice(list)Random element from listrandomChoice([1,2,3])2
shuffle(list)Shuffled copy (Fisher-Yates)shuffle([1,2,3])[3,1,2]

List Functions

FunctionDescriptionExample
length(list)Number of elementslength([1,2,3])3
head(list)First elementhead([1,2,3])1
tail(list)All except firsttail([1,2,3])[2,3]
push(list, item)Append itempush([1,2], 3)[1,2,3]
concat(a, b)Join two listsconcat([1,2], [3,4])[1,2,3,4]
reverse(list)Reverse orderreverse([1,2,3])[3,2,1]
zip(a, b)Pair elementszip([1,2], ["a","b"])[[1,"a"],[2,"b"]]
isEmpty(list)Check if emptyisEmpty([])true
range(start, end)Generate rangerange(1, 4)[1,2,3]
take(list, n)First n elementstake([1,2,3,4], 2)[1,2]
at(list, index)Element at indexat([1,2,3], 1)2
partition(list, fn)Split by predicatepartition([1,2,3], (x) -> x > 1)[[2,3], [1]]
iterations(n, fn)Apply fn n timesiterations(3, (x) -> x * 2)(1)8

Higher-Order List Functions

All callbacks receive (element, index):

[1, 2, 3] /> map((x) -> x * 2)              -- [2, 4, 6]
[1, 2, 3] /> map((x, i) -> `{i}: {x}`) -- ["0: 1", "1: 2", "2: 3"]

[1, 2, 3, 4] /> filter((x) -> x > 2) -- [3, 4]
[1, 2, 3, 4] /> filter((_, i) -> i < 2) -- [1, 2]

[1, 2, 3] /> reduce(0, (acc, x) -> acc + x) -- 6
[1, 2, 3] /> reduce("", (acc, x, i) -> acc ++ `{i}`) -- "012"

Tuple Functions

FunctionDescriptionExample
fst(tuple)First elementfst((1, 2))1
snd(tuple)Second elementsnd((1, 2))2

String Functions

FunctionDescriptionExample
split(str, delim)Split stringsplit("a,b,c", ",")["a","b","c"]
lines(str)Split by newlineslines("a\nb")["a","b"]
charAt(str, i)Character at indexcharAt("hello", 1)"e"
chars(str)Split to charschars("hi")["h","i"]
join(list, delim?)Join to stringjoin(["a","b"], "-")"a-b"
toUpperCase(str)Convert to uppercasetoUpperCase("hello")"HELLO"
toLowerCase(str)Convert to lowercasetoLowerCase("HELLO")"hello"
replace(str, search, repl)Replace all occurrencesreplace("aXbXc", "X", "-")"a-b-c"
replaceFirst(str, search, repl)Replace first occurrencereplaceFirst("aXbXc", "X", "-")"a-bXc"
startsWith(str, prefix)Check prefixstartsWith("hello", "he")true
endsWith(str, suffix)Check suffixendsWith("hello", "lo")true
padEnd(str, len, char?)Pad endpadEnd("hi", 5)"hi "
padStart(str, len, char?)Pad startpadStart("hi", 5)" hi"
trim(str)Remove whitespacetrim(" hi ")"hi"
trimEnd(str)Remove trailing wstrimEnd("hi ")"hi"
indexOf(str, search)Find indexindexOf("hello", "l")2
includes(str, item)Contains substringincludes("hello", "ell")true
repeat(str, n)Repeat stringrepeat("ab", 3)"ababab"
slice(str, start, end?)Extract substringslice("hello", 1, 3)"el"
toString(value)Convert to stringtoString(42)"42"

Set Operations (on Lists)

FunctionDescriptionExample
listSet(list)Unique elementslistSet([1,1,2])[1,2]
setAdd(list, item)Add if not presentsetAdd([1,2], 3)[1,2,3]
setHas(list, item)Check membershipsetHas([1,2], 2)true

JSON Functions

FunctionDescriptionExample
parseJson(str)Parse JSON stringparseJson('{"a":1}'){a: 1}
toJson(value)Convert to JSON stringtoJson({a: 1})'{"a":1}'
toJson(value, indent)Convert with indentationtoJson({a: 1}, 2)
prettyJson(value)Pretty-print (2 spaces)prettyJson({a: 1})
-- Parse JSON
let data = parseJson('{"name": "Alice", "scores": [90, 85]}')
data.name /> print -- "Alice"
data.scores /> head -- 90

-- Convert to JSON
let user = { name: "Bob", age: 30 }
user /> toJson /> print -- '{"name":"Bob","age":30}'
user /> prettyJson /> print
-- {
-- "name": "Bob",
-- "age": 30
-- }

Date/Time Functions

FunctionDescriptionExample
now()Current timestamp (ms)now()1702500000000
today()Current date recordtoday(){year: 2024, ...}
date(timestamp)Date from timestampdate(1702500000000)
date(str)Parse date stringdate("2024-01-15")
date(y, m, d, ...)Create from componentsdate(2024, 1, 15)
formatDate(d, fmt?)Format as stringformatDate(d, "YYYY-MM-DD")
parseDate(str)Parse date stringparseDate("2024-01-15")
addDays(d, n)Add daysaddDays(d, 7)
addHours(d, n)Add hoursaddHours(d, 2)
addMinutes(d, n)Add minutesaddMinutes(d, 30)
diffDates(d1, d2)Difference in msdiffDates(d1, d2)

Date Record Fields

Date functions return records with these fields:

let d = today()
d.year -- 2024
d.month -- 1-12
d.day -- 1-31
d.hour -- 0-23
d.minute -- 0-59
d.second -- 0-59
d.millisecond -- 0-999
d.dayOfWeek -- 0 (Sun) - 6 (Sat)
d.timestamp -- Unix timestamp in ms

Format Strings

FormatDescriptionExample Output
"ISO"ISO 8601 (default)"2024-01-15T10:30:00.000Z"
"date"Date string"Mon Jan 15 2024"
"time"Time string"10:30:00 GMT+0000"
"locale"Locale string"1/15/2024, 10:30:00 AM"
"YYYY-MM-DD"Custom format"2024-01-15"
"HH:mm:ss"Custom time"10:30:00"
-- Date arithmetic
let start = date(2024, 1, 15)
let end = start /> addDays(30)
let diff = diffDates(end, start) / (24 * 60 * 60 * 1000) -- 30 days

-- Formatting
now() /> formatDate("YYYY-MM-DD") /> print -- "2024-12-10"
today() /> formatDate("locale") /> print

I/O Functions

FunctionDescriptionExample
print(value)Print and return valueprint("hi") → prints "hi", returns "hi"

Async Functions

FunctionDescriptionExample
delay(ms, value?)Resolve after delaydelay(100)
parallel(list, fn, opts?)Concurrent mapparallel(urls, fetch, { limit: 3 })
race(fns)First to completerace([fn1, fn2])
then(promise, fn)Chain transformationthen(promise, (x) -> x * 2)

Special Functions

FunctionDescriptionExample
breakPieces(shape)Parse ASCII diagram into minimal closed piecesbreakPieces(asciiShape)

Decorators

Function Decorators

DecoratorDescriptionExample
#logLog inputs/outputs(x) -> x * 2 #log
#log_verboseDetailed logging with timing(x) -> x * 2 #log_verbose
#memoCache results(x) -> expensive(x) #memo
#timeLog execution time(x) -> slow(x) #time
#retry(n)Retry on failure(x) -> risky(x) #retry(3)
#timeout(ms)Fail if exceeds time(x) -> slow(x) #timeout(1000)
#validateRuntime type checking(x) -> x :: Int :> Int #validate
#pureWarn if side effects(x) -> x * 2 #pure
#asyncMark as async() -> delay(100) #async
#traceDeep call logging(x) -> recurse(x) #trace

Type Coercion Decorators

DecoratorDescriptionExample
#coerce(Type)Coerce input to type(x) -> x * 2 #coerce(Int)
#parseParse string as JSON/number(x) -> x #parse
#stringifyConvert output to string(x) -> x #stringify
#tease(Type)Best-effort extraction(x) -> x #tease(Int) extracts 42 from "42px"

Pipeline Decorators

DecoratorDescriptionExample
#logLog pipeline input/output/> fn1 /> fn2 #log
#log_verboseStage-by-stage logging/> fn1 /> fn2 #log_verbose
#memoCache pipeline results/> fn1 /> fn2 #memo
#timeLog total execution time/> fn1 /> fn2 #time
#tapInspect without modifying/> fn1 /> fn2 #tap
#tap("fn")Call named function/> fn1 /> fn2 #tap("debug")
#debugStage-by-stage execution log/> fn1 /> fn2 #debug
#profileTiming breakdown per stage/> fn1 /> fn2 #profile
#traceNested call tracing/> fn1 /> fn2 #trace