Standard Library
Core
| Function | Description | Example |
|---|---|---|
| (import path) | Import a module file and execute it in the current context (alias: import-file, module/import) | (import "lib/utils.elle") |
Math
| Function | Description | Example |
|---|---|---|
| (math/acos x) | Returns the arccosine of a number (in radians). (alias: acos) | (math/acos 1) |
| (math/asin x) | Returns the arcsine of a number (in radians). (alias: asin) | (math/asin 1) |
| (math/atan x) | Returns the arctangent of a number (in radians). (alias: atan) | (math/atan 1) |
| (math/atan2 y x) | Returns the arctangent of y/x (in radians), using the signs of both arguments to determine the quadrant. (alias: atan2) | (math/atan2 1 1) |
| (math/cbrt x) | Returns the cube root of a number. (alias: cbrt) | (math/cbrt 27) |
| (math/ceil x) | Returns the smallest integer greater than or equal to x. (alias: ceil) | (math/ceil 3.2) |
| (math/cos x) | Returns the cosine of a number (in radians). (alias: cos) | (math/cos 0) |
| (math/cosh x) | Returns the hyperbolic cosine of a number. (alias: cosh) | (math/cosh 1) |
| (math/e) | The mathematical constant e (Euler's number). (alias: e) | (math/e) |
| (math/exp x) | Returns e raised to the power of x. (alias: exp) | (math/exp 1) |
| (math/exp2 x) | Returns 2 raised to the power of x. (alias: exp2) | (math/exp2 3) |
| (math/floor x) | Returns the largest integer less than or equal to x. (alias: floor) | (math/floor 3.7) |
| (math/log x base) | Returns the natural logarithm of x, or logarithm with specified base. (alias: log) | (math/log 2.718281828) |
| (math/log10 x) | Returns the base-10 logarithm of a number. (alias: log10) | (math/log10 100) |
| (math/log2 x) | Returns the base-2 logarithm of a number. (alias: log2) | (math/log2 8) |
| (math/pi) | The mathematical constant pi (π). (alias: pi) | (math/pi) |
| (math/pow x y) | Returns x raised to the power of y. (alias: pow) | (math/pow 2 8) |
| (math/round x) | Returns the nearest integer to x. (alias: round) | (math/round 3.5) |
| (math/sin x) | Returns the sine of a number (in radians). (alias: sin) | (math/sin 0) |
| (math/sinh x) | Returns the hyperbolic sine of a number. (alias: sinh) | (math/sinh 1) |
| (math/sqrt x) | Returns the square root of a number. (alias: sqrt) | (math/sqrt 16) |
| (math/tan x) | Returns the tangent of a number (in radians). (alias: tan) | (math/tan 0) |
| (math/tanh x) | Returns the hyperbolic tangent of a number. (alias: tanh) | (math/tanh 1) |
| (math/trunc x) | Returns the integer part of a number, truncating toward zero. (alias: trunc) | (math/trunc 3.7) |
String Operations
| Function | Description | Example |
|---|---|---|
| (@string) | Create a mutable string from byte arguments. | (@string 72 101 108 108 111) |
| (string/contains? s substr) | Check if string contains substring. | (string/contains? "hello" "ell") #=> true |
| (string/ends-with? s suffix) | Check if string ends with suffix. (alias: string-ends-with?) | (string/ends-with? "hello" "lo") #=> true |
| (string/find haystack needle offset) | Find the grapheme index of a substring, with optional start offset. (alias: string-index, string/index, string-find) | (string/find "hello" "ll") #=> 2 |
| (string/format template args) | Format a template string with positional or named arguments. | (string/format "{} + {} = {}" 1 2 3) #=> "1 + 2 = 3" |
| (string/join lst sep) | Join list of strings with separator. (alias: string-join) | (string/join (list "a" "b" "c") ",") #=> "a,b,c" |
| (string/lowercase s) | Convert string to lowercase. (alias: string/downcase, string-downcase) | (string/lowercase "HELLO") #=> "hello" |
| (string/repeat s n) | Repeat a string N times. (alias: string-repeat) | (string/repeat "ab" 3) #=> "ababab" |
| (string/replace s old new) | Replace all occurrences of old substring with new. (alias: string-replace) | (string/replace "hello" "l" "L") #=> "heLLo" |
| (string/size-of s) | Return the UTF-8 byte length of a string. | (string/size-of "café") #=> 5 |
| (string/split s delim) | Split string by delimiter, returning an array of substrings. (alias: string-split) | (string/split "a,b,c" ",") #=> ["a" "b" "c"] |
| (string/starts-with? s prefix) | Check if string starts with prefix. (alias: string-starts-with?) | (string/starts-with? "hello" "he") #=> true |
| (string/trim s) | Remove leading and trailing whitespace. (alias: string-trim) | (string/trim " hello ") #=> "hello" |
| (string/uppercase s) | Convert string to uppercase. (alias: string/upcase, string-upcase) | (string/uppercase "hello") #=> "HELLO" |
| (uri-encode str) | Percent-encode a string per RFC 3986. | (uri-encode "hello world") ;=> "hello%20world" |
Arrays
| Function | Description | Example |
|---|---|---|
| (@array) | Create a mutable array from arguments. | (@array 1 2 3) #=> @[1 2 3] |
| (array) | Create an immutable array from arguments. | (array 1 2 3) #=> [1 2 3] |
| (array/new n fill) | Create array of n elements, all set to fill value. | (array/new 3 0) #=> [0 0 0] |
| (insert arr idx val) | Insert element at index in array. Mutates in place, returns the same array. | (insert @[1 3] 1 2) #=> @[1 2 3] |
| (pop arr) | Remove and return last element from array. Mutates in place. | (pop @[1 2 3]) #=> 3 |
| (popn arr n) | Remove and return last n elements from array as a new array. Mutates original. | (popn @[1 2 3 4] 2) #=> @[3 4] |
| (push arr val) | Append element to end of array. Mutates in place, returns the same array. | (push @[1 2] 3) #=> @[1 2 3] |
| (remove arr idx count) | Remove element(s) at index from array. Mutates in place, returns the same array. | (remove @[1 2 3] 1) #=> @[1 3] |
Structs
| Function | Description | Example |
|---|---|---|
| (@struct) | Create a mutable struct from key-value pairs | (@struct :a 1 :b 2) |
| (deep-freeze value) | Recursively freeze a value and all its contents. Converts mutable collections to immutable and recurses into elements. Atoms and non-collection types are returned as-is. | (deep-freeze @[@[1 2] @{:a 3}]) |
| (del collection key) | Delete a key from a struct | (del (@struct :a 1) :a) |
| (freeze collection) | Convert a mutable collection to its immutable equivalent. Handles @array, @struct, @set, @string (requires valid UTF-8), @bytes. Returns immutable values as-is. | (freeze @{:a 1 :b 2}) |
| (get collection key default) | Get a value from a collection (tuple, array, string, struct) by index or key, with optional default | (get [1 2 3] 0) |
| (has? collection key-or-value) | Check if a collection has a key, element, or substring. Works on structs (key lookup), sets (membership), and strings (substring check). (alias: has-key?, contains?) | (has? {:a 1} :a) #=> true (has? |1 2 3| 2) #=> true (has? "hello" "ell") #=> true |
| (keys collection) | Get all keys from a struct as a list | (keys (@struct :a 1 :b 2)) |
| (pairs struct) | Iterate over struct key-value pairs as [key value] arrays. | (pairs {:a 1 :b 2}) |
| (put collection key-or-value value) | Put a value into a collection. For structs/arrays/strings: (put coll key value). For sets: (put set value). | (put {:a 1} :b 2) #=> {:a 1 :b 2} (put |1 2| 3) #=> |1 2 3| |
| (struct) | Create an immutable struct from key-value pairs | (struct :a 1 :b 2) |
| (thaw collection) | Convert an immutable collection to its mutable equivalent. Handles array, struct, set, string, bytes. Returns mutable values as-is. | (thaw {:a 1 :b 2}) |
| (values collection) | Get all values from a struct as a list | (values (@struct :a 1 :b 2)) |
JSON
| Function | Description | Example |
|---|---|---|
| (json/parse json-string :keys :keyword) | Parse a JSON string into Elle values. Accepts optional :keys :keyword to use keyword keys in parsed structs instead of string keys. (alias: json-parse) | (json/parse "{\"name\": \"Alice\", \"age\": 30}" :keys :keyword) |
| (json/pretty value) | Serialize an Elle value to pretty-printed JSON with 2-space indentation (alias: json-serialize-pretty) | (json/pretty (list 1 2 3)) |
| (json/serialize value) | Serialize an Elle value to compact JSON (alias: json-serialize) | (json/serialize (@struct :name "Bob" :age 25)) |
File I/O
| Function | Description | Example |
|---|---|---|
| (file/append path content) | Append string content to a file (alias: append-file) | (file/append "log.txt" "new line") |
| (file/copy src dst) | Copy a file (alias: copy-file) | (file/copy "source.txt" "dest.txt") |
| (file/delete path) | Delete a file (alias: delete-file) | (file/delete "temp.txt") |
| (file/delete-dir path) | Delete a directory (must be empty) (alias: delete-directory) | (file/delete-dir "empty-dir") |
| (file/lines path) | Read lines from a file and return as a list of strings (alias: read-lines) | (file/lines "data.txt") |
| (file/ls path) | List directory contents (alias: list-directory) | (file/ls ".") |
| (file/lstat path) | Get filesystem metadata as a struct (does not follow symlinks) | (file/lstat "link.txt") |
| (file/mkdir path) | Create a directory (alias: create-directory) | (file/mkdir "new-dir") |
| (file/mkdir-all path) | Create a directory and all parent directories (alias: create-directory-all) | (file/mkdir-all "a/b/c") |
| (file/read path) | Read entire file as a string (alias: slurp) | (file/read "data.txt") |
| (file/rename old-path new-path) | Rename a file (alias: rename-file) | (file/rename "old.txt" "new.txt") |
| (file/size path) | Get file size in bytes (alias: file-size) | (file/size "data.txt") |
| (file/stat path) | Get filesystem metadata as a struct (follows symlinks) | (file/stat "data.txt") |
| (file/write path content) | Write string content to a file (overwrites if exists) (alias: spit) | (file/write "output.txt" "hello") |
Function Introspection
| Function | Description | Example |
|---|---|---|
| (fn/arity value) | Returns closure arity as int, pair, or nil (alias: arity) | (fn/arity (fn (x y) x)) |
| (fn/bytecode-size value) | Returns size of bytecode in bytes, or nil (alias: bytecode-size) | (fn/bytecode-size (fn (x) x)) |
| (fn/captures value) | Returns number of captured variables, or nil (alias: captures) | (fn/captures (let ((x 1)) (fn () x))) |
| (fn/disasm closure) | Disassemble a closure's bytecode into a list of instruction strings. (alias: disbit, fn/disbit) | (fn/disasm (fn (x) x)) |
| (fn/disasm-jit closure) | Disassemble a closure's JIT-compiled Cranelift IR, or nil if not JIT'd. (alias: disjit, fn/disjit) | (fn/disasm-jit (fn (x) x)) |
| (fn/errors? value) | Returns true if closure may error | (fn/errors? (fn (x) (/ 1 x))) |
| (fn/flow closure-or-fiber) | Return the LIR control flow graph of a closure or fiber as structured data. | (fn/flow (fn (x y) (+ x y))) |
| (fn/mutates-params? value) | Returns true if closure mutates any parameters (alias: mutates-params?) | (fn/mutates-params? (fn (x) (assign x 1))) |
| (squelch closure signals) | Return a new closure that intercepts and converts the specified signals to :error at runtime. The second argument can be a keyword, set, array, list, or integer of signal bits. | (squelch (fn () (yield 1)) |:yield|) |
Fibers
| Function | Description | Example |
|---|---|---|
| (fiber/abort fiber error?) | Gracefully terminate a fiber by injecting an error and resuming it. Defer/protect blocks run. (alias: abort) | (fiber/abort f) (fiber/abort f :reason) |
| (fiber/bits fiber) | Get the signal bits from the fiber's last signal | (fiber/bits f) |
| (fiber/cancel fiber error?) | Hard-kill a fiber. Sets it to :error without unwinding. No defer/protect runs. Supports self-cancel. (alias: cancel) | (fiber/cancel f) (fiber/cancel f :reason) |
| (fiber/child fiber) | Get the most recently resumed child fiber, or nil if none | (fiber/child f) |
| (fiber/clear-fuel fiber) | Remove the instruction budget, restoring unlimited execution. | (fiber/clear-fuel f) |
| (fiber/emit bits value) | Emit a signal from the current fiber (alias: emit) | (emit 2 42) |
| (fiber/fuel fiber) | Read remaining fuel. Returns integer or nil if unlimited. | (fiber/fuel f) |
| (fiber/mask fiber) | Get the fiber's signal mask | (fiber/mask f) |
| (fiber/new closure mask) | Create a fiber from a closure with a signal mask (alias: fiber) | (fiber/new (fn [] 42) 0) |
| (fiber/parent fiber) | Get the parent fiber, or nil if this is a top-level fiber | (fiber/parent f) |
| (fiber/propagate fiber) | Propagate a caught signal from a child fiber, preserving the child chain | (fiber/propagate f) |
| (fiber/resume fiber value) | Resume a fiber, optionally delivering a value (alias: resume) | (fiber/resume f) |
| (fiber/set-fuel fiber n) | Set the instruction budget on a fiber. n is a non-negative integer. | (fiber/set-fuel f 10000) |
| (fiber/status fiber) | Get the fiber's lifecycle status (:new, :alive, :suspended, :dead, :error) | (fiber/status f) |
| (fiber/value fiber) | Get the signal payload from the fiber's last signal | (fiber/value f) |
| (fiber? value) | Check if a value is a fiber | (fiber? f) |
Coroutines
| Function | Description | Example |
|---|---|---|
| (coro/>iterator coroutine) | Convert a coroutine to an iterator (identity — fibers are iterable) | (coro/>iterator co) |
| (coro/done? coroutine) | Check if a coroutine is done (dead or errored) | (coro/done? co) |
| (coro/new closure) | Create a coroutine (fiber with SIG_YIELD mask) from a closure (alias: make-coroutine) | (coro/new (fn [] (+ 1 2))) |
| (coro/resume coroutine value) | Resume a coroutine, optionally delivering a value | (coro/resume co) |
| (coro/status coroutine) | Get the status of a coroutine (:new, :alive, :paused, :dead, :error) | (coro/status co) |
| (coro/value coroutine) | Get the signal payload from a coroutine's last signal | (coro/value co) |
Clock
| Function | Description | Example |
|---|---|---|
| (clock/cpu) | Return thread CPU time in seconds | (clock/cpu) |
| (clock/monotonic) | Return seconds elapsed since process start (monotonic clock) | (clock/monotonic) |
| (clock/realtime) | Return seconds since Unix epoch (wall clock) | (clock/realtime) |
Time
| Function | Description | Example |
|---|---|---|
| (time/sleep seconds) | Sleep for the specified number of seconds (blocks the thread) | (time/sleep 1.5) |
Metaprogramming
| Function | Description | Example |
|---|---|---|
| (arena/allocs thunk) | Run thunk, return (result . net-allocs) where net-allocs is the net heap objects allocated. | (arena/allocs (fn [] (cons 1 2))) |
| (arena/bytes) | Return bytes consumed by the current FiberHeap. | (arena/bytes) |
| (arena/checkpoint) | Return an opaque checkpoint for the current arena position. Pass to arena/reset only. The return value is an opaque external — do not treat it as an integer. Dangerous: invalidates all Values allocated after the mark. | (let ((m (arena/checkpoint))) (cons 1 2) (arena/reset m)) |
| (arena/count) | Return current heap object count. (alias: arena-count) | (arena/count) |
| (arena/object-limit) | Get current object limit. Returns int or nil (unlimited). | (arena/object-limit) |
| (arena/peak) | Return peak object count (high-water mark). | (arena/peak) |
| (arena/reset mark) | Reclaim arena objects allocated after checkpoint mark. Runs destructors for freed objects. Bump memory is not reclaimed. Dangerous: any Value pointing into the freed region is now invalid. | (let ((m (arena/checkpoint))) (cons 1 2) (arena/reset m)) |
| (arena/reset-peak) | Reset peak to current count. Returns previous peak. | (arena/reset-peak) |
| (arena/set-object-limit n) | Set max heap object count. Pass nil to remove limit. Returns previous limit or nil. | (arena/set-object-limit 10000) |
| (arena/stats fiber?) | Return heap arena statistics. With no args: stats for the current fiber. With a fiber arg: stats for a suspended/dead fiber. Returns a struct with :object-count, :peak-count, :allocated-bytes, :object-limit, :scope-depth, :dtor-count, :root-live-count, :root-alloc-count, :shared-count, :active-allocator, :scope-enter-count, :scope-dtor-count. (alias: vm/arena, arena-stats) | (arena/stats) |
| (jit/rejections) | List closures rejected from JIT compilation. Returns list of {:name :reason :calls} structs sorted by call count ascending. | (jit/rejections) |
| (meta/datum->syntax context datum) | Create a syntax object with lexical context from another syntax object (alias: datum->syntax) | (meta/datum->syntax stx 'x) |
| (meta/gensym prefix) | Generate a unique symbol with optional prefix (alias: gensym) | (meta/gensym "tmp") |
| (meta/origin f) | Return the source location of a closure as {:file :line :col}, or nil if unavailable. | (defn foo () 42) (meta/origin foo) |
| (meta/syntax->datum stx) | Strip scope information from a syntax object, returning the plain value (alias: syntax->datum) | (meta/syntax->datum stx) |
| (meta/syntax->list stx) | Convert a syntax list to an immutable array of syntax objects (alias: syntax->list) | (meta/syntax->list stx) |
| (meta/syntax-e stx) | Shallow-unwrap a syntax object: returns atoms as plain values, compounds unchanged (alias: syntax-e) | (meta/syntax-e stx) |
| (meta/syntax-first stx) | Return the first element of a syntax list as a syntax object (alias: syntax-first) | (meta/syntax-first stx) |
| (meta/syntax-keyword? stx) | Return true if stx is a syntax object wrapping a keyword (alias: syntax-keyword?) | (meta/syntax-keyword? stx) |
| (meta/syntax-list? stx) | Return true if stx is a syntax object wrapping a list (including empty) (alias: syntax-list?) | (meta/syntax-list? stx) |
| (meta/syntax-nil? stx) | Return true if stx is a syntax object wrapping nil (alias: syntax-nil?) | (meta/syntax-nil? stx) |
| (meta/syntax-pair? stx) | Return true if stx is a syntax object wrapping a non-empty list (alias: syntax-pair?) | (meta/syntax-pair? stx) |
| (meta/syntax-rest stx) | Return a syntax list of all but the first element (alias: syntax-rest) | (meta/syntax-rest stx) |
| (meta/syntax-symbol? stx) | Return true if stx is a syntax object wrapping a symbol (alias: syntax-symbol?) | (meta/syntax-symbol? stx) |
| (read str) | Parse the first form from a string, returning a value | (read "(+ 1 2)") #=> (+ 1 2) |
| (read-all str) | Parse all forms from a string, returning a list of values | (read-all "1 2 3") #=> (1 2 3) |
| (signals) | Return the signal registry as a struct mapping keywords to bit positions. | (signals) |
| (vm/list-primitives category?) | List registered names as a sorted list of symbols. Optional category filter. (alias: list-primitives) | (vm/list-primitives) (vm/list-primitives :math) (vm/list-primitives :"special form") |
| (vm/primitive-meta name) | Get structured metadata for a primitive as a struct. (alias: primitive-meta) | (struct-get (vm/primitive-meta "cons") "doc") #=> "Construct a cons cell..." |
| (vm/query op arg) | Query VM state (call-count, doc, global?, fiber/self) | (vm/query "call-count" some-fn) |
Debugging
| Function | Description | Example |
|---|---|---|
| (debug/memory) | Returns memory usage statistics as (rss-bytes virtual-bytes) (alias: memory-usage) | (debug/memory) |
| (debug/print value) | Prints a value with debug information to stderr (alias: debug-print) | (debug/print 42) |
| (debug/trace label value) | Traces execution with a label, prints to stderr, returns value (alias: trace) | (debug/trace "x" 42) |
Bitwise Operations
| Function | Description | Example |
|---|---|---|
| (bit/and xs) | Bitwise AND of all arguments | (bit/and 12 10) #=> 8 |
| (bit/not x) | Bitwise NOT of argument | (bit/not 0) #=> -1 |
| (bit/or xs) | Bitwise OR of all arguments | (bit/or 12 10) #=> 14 |
| (bit/shl x n) | Left shift first argument by second argument (clamped to 0-63). (alias: bit/shift-left) | (bit/shl 1 3) #=> 8 |
| (bit/shr x n) | Arithmetic right shift first argument by second argument (clamped to 0-63). (alias: bit/shift-right) | (bit/shr 8 2) #=> 2 |
| (bit/xor xs) | Bitwise XOR of all arguments | (bit/xor 12 10) #=> 6 |
FFI (Foreign Function Interface)
| Function | Description | Example |
|---|---|---|
| (ffi/align type) | Get the alignment of a C type in bytes. | (ffi/align :double) #=> 8 |
| (ffi/array elem-type count) | Create an array type descriptor from element type and count. | (ffi/array :i32 10) |
| (ffi/call fn-ptr sig) | Call a C function through libffi. | (ffi/call sqrt-ptr sig 2.0) |
| (ffi/callback sig closure) | Create a C function pointer from an Elle closure. Returns a pointer. | (ffi/callback (ffi/signature :int [:ptr :ptr]) (fn (a b) 0)) |
| (ffi/callback-free ptr) | Free a callback created by ffi/callback. | (ffi/callback-free cb-ptr) |
| (ffi/free ptr) | Free C memory. | (ffi/free ptr) |
| (ffi/lookup lib name) | Look up a symbol in a loaded library. | (ffi/lookup lib "strlen") |
| (ffi/malloc size) | Allocate C memory. | (ffi/malloc 100) |
| (ffi/native path) | Load a shared library. Pass nil for the current process. | (ffi/native "libm.so.6") |
| (ffi/read ptr type) | Read a typed value from C memory. | (ffi/read ptr :i32) |
| (ffi/signature return-type arg-types fixed-args) | Create a reified function signature. Optional third arg for variadic functions. | (ffi/signature :int [:ptr :size :ptr :int] 3) |
| (ffi/size type) | Get the size of a C type in bytes. | (ffi/size :i32) #=> 4 |
| (ffi/string ptr max-len) | Read a null-terminated C string from a pointer. | (ffi/string ptr) |
| (ffi/struct fields) | Create a struct type descriptor from field types. | (ffi/struct [:i32 :double :ptr]) |
| (ffi/write ptr type value) | Write a typed value to C memory. | (ffi/write ptr :i32 42) |
allocator
| Function | Description | Example |
|---|---|---|
| (allocator/install allocator) | Install a custom allocator on the current fiber's heap. INTERNAL: use via with-allocator macro only. | |
| (allocator/uninstall) | Uninstall the current custom allocator, freeing remaining custom objects. INTERNAL: use via with-allocator macro only. |
arithmetic
| Function | Description | Example |
|---|---|---|
| (% a b) | Truncated remainder. Result has same sign as dividend. | (% 17 5) #=> 2 (% -17 5) #=> -2 |
| ( xs) | Multiply all arguments. Returns 1 for no arguments. | () #=> 1 ( 2 3 4) #=> 24 |
| (+ xs) | Sum all arguments. Returns 0 for no arguments. | (+) #=> 0 (+ 1 2 3) #=> 6 |
| (- x ys) | Subtract arguments left-to-right. Single arg negates. | (- 10 3 2) #=> 5 (- 5) #=> -5 |
| (/ x ys) | Divide arguments left-to-right. Single arg takes reciprocal. | (/ 10 2) #=> 5 (/ 2) #=> 0.5 |
| (abs x) | Absolute value. | (abs -5) #=> 5 (abs 3) #=> 3 |
| (even? n) | Test if integer is even. | (even? 4) #=> true (even? 3) #=> false |
| (max xs) | Maximum of all arguments. | (max 3 1 4) #=> 4 |
| (min xs) | Minimum of all arguments. | (min 3 1 4) #=> 1 |
| (mod a b) | Euclidean modulo. Result has same sign as divisor. | (mod 17 5) #=> 2 (mod -17 5) #=> 3 |
| (odd? n) | Test if integer is odd. | (odd? 3) #=> true (odd? 4) #=> false |
| (rem a b) | Truncated remainder. Result has same sign as dividend. | (rem 17 5) #=> 2 (rem -17 5) #=> -2 |
box
| Function | Description | Example |
|---|---|---|
| (box value) | Create a mutable box containing a value. | (box 42) #=> #<box> |
| (rebox box value) | Modify the value in a box and return the new value. | (let ((c (box 1))) (rebox c 2) (unbox c)) #=> 2 |
| (unbox box) | Extract the value from a box. | (unbox (box 42)) #=> 42 |
bytes
| Function | Description | Example |
|---|---|---|
| (@bytes) | Create mutable bytes. Accepts integers (0-255), or a single string/keyword. | (@bytes 72 101 108 108 111) (@bytes "hello") |
| (bytes) | Create immutable bytes. Accepts integers (0-255), or a single string/keyword. | (bytes 72 101 108 108 111) (bytes "hello") |
| (seq->hex x) | Convert bytes, @bytes, array, @array, list, or integer to a lowercase hex string. Mutable input (@bytes, @array) produces @string; all other input produces string. Integer input uses big-endian minimal-byte encoding (0 → "00"). Aliases: bytes->hex, bytes->hex-string. (alias: bytes->hex, bytes->hex-string) | (seq->hex (bytes 72 101 108)) ;=> "48656c" (seq->hex [72 101 108]) ;=> "48656c" (seq->hex 255) ;=> "ff" |
| (slice coll start end?) | Slice a sequence from start to end index. If end is omitted, slice to end of sequence. Returns same type as input. | (slice [1 2 3 4 5] 1 3) (slice "hello" 1) |
chan
| Function | Description | Example |
|---|---|---|
| (chan &opt capacity) | Create a channel. Returns [sender receiver]. Optional capacity for bounded channel. (alias: chan/new) | (chan) |
| (chan/clone sender) | Clone a sender. Multiple senders can feed the same channel. | (chan/clone sender) |
| (chan/close sender) | Close a sender. Receivers will get :disconnected after buffered messages drain. | (chan/close sender) |
| (chan/close-recv receiver) | Close a receiver. Senders will get :disconnected on next send. | (chan/close-recv receiver) |
| (chan/recv receiver) | Non-blocking receive. Returns [:ok msg], [:empty], or [:disconnected]. | (chan/recv receiver) |
| (chan/select receivers &opt timeout-ms) | Block until one receiver has a message. Returns [index msg] or [:timeout]. | (chan/select @[r1 r2]) |
| (chan/send sender msg) | Non-blocking send. Returns [:ok], [:full], or [:disconnected]. | (chan/send sender 42) |
collection
| Function | Description | Example |
|---|---|---|
| (range start-or-end end step) | Generate a range of numbers as an array. (range end), (range start end), (range start end step). | (range 5) #=> @[0 1 2 3 4] |
| (sort coll) | Sort a collection in ascending order using the built-in value ordering. Type-preserving: @arrays mutated in place, arrays and lists return new sorted values. | (sort @[3 1 2]) #=> @[1 2 3] (sort ["b" "a" "c"]) #=> ["a" "b" "c"] |
comparison
| Function | Description | Example |
|---|---|---|
| (< a b) | Test strictly ascending order. Chained: (< a b c) means a < b and b < c. Works on numbers, strings, and keywords. | (< 1 2 3) #=> true (< "a" "b" "c") #=> true (< :apple :banana :cherry) #=> true |
| (<= a b) | Test non-descending order. Chained: (<= a b c) means a <= b and b <= c. Works on numbers, strings, and keywords. | (<= 1 2 2 3) #=> true (<= "a" "b" "b" "c") #=> true |
| (= a b) | Test equality of values. Numeric-aware: (= 1 1.0) is true. Chained: (= a b c) means all are equal. (alias: eq?) | (= 1 1) #=> true (= 1 1.0) #=> true (= 1 2 1) #=> false |
| (> a b) | Test strictly descending order. Chained: (> c b a) means c > b and b > a. Works on numbers, strings, and keywords. | (> 3 2 1) #=> true (> "c" "b" "a") #=> true (> :cherry :banana :apple) #=> true |
| (>= a b) | Test non-ascending order. Chained: (>= c b a) means c >= b and b >= a. Works on numbers, strings, and keywords. | (>= 3 2 2 1) #=> true (>= "c" "b" "b" "a") #=> true |
| (compare a b) | Three-way comparison. Returns -1 if a < b, 0 if a = b, 1 if a > b. Uses the same total ordering as sort. Useful for writing comparators: (sort-with (fn (a b) (compare b a)) coll) sorts descending. | (compare 1 2) #=> -1 (compare 2 2) #=> 0 (compare 3 2) #=> 1 (compare "a" "b") #=> -1 |
| (hash value) | Hash any value to an integer. Equal values produce equal hashes. Uses the same structural hashing as hash-map/hash-set internals. | (hash 42) #=> <integer> (= (hash :foo) (hash :foo)) #=> true |
| (identical? a b) | Test strict identity. No numeric coercion: (identical? 1 1.0) is false. | (identical? 1 1) #=> true (identical? 1 1.0) #=> false |
| (not= a b) | Test inequality of values. Numeric-aware: (not= 1 1.0) is false. Returns true if the two values are not equal. | (not= 1 2) #=> true (not= 1 1) #=> false (not= 1 1.0) #=> false |
control
| Function | Description | Example |
|---|---|---|
| (assert value message?) | Assert that value is truthy. Signals {:error :failed-assertion :message msg} if not. Returns value if truthy. | (assert true) (assert (> x 0) "x must be positive") |
conversion
| Function | Description | Example |
|---|---|---|
| (float x) | Convert value to float. Accepts int, float, string, or keyword. | (float 42) #=> 42.0 (float "3.14") #=> 3.14 |
| (integer x radix?) | Convert value to integer (i64). Accepts int, float, string, or keyword. With an optional radix (2–36), parses a string/keyword in the given base. (alias: int) | (integer 3.7) #=> 3 (integer "42") #=> 42 (integer "ff" 16) #=> 255 (integer "1010" 2) #=> 10 |
| (keyword str) | Convert a string to a keyword. (alias: string->keyword) | (keyword "foo") |
| (number->string n radix?) | Convert a number to string. With an optional radix (2–36), converts an integer to the given base (lowercase, no prefix). | (number->string 42) #=> "42" (number->string 255 16) #=> "ff" (number->string -255 16) #=> "-ff" |
| (string values) | Convert values to string. Multiple arguments are concatenated. (alias: any->string, symbol->string) | (string "count: " 42) #=> "count: 42" |
elle
| Function | Description | Example |
|---|---|---|
| (elle/epoch n) | Return the current language epoch. With 1 arg, returns the arg (compile-time declaration form). | (elle/epoch) #=> 3 |
| (elle/info) | Get package information (name, version, description) (alias: pkg/info, package-info) | (elle/info) |
| (elle/version) | Get the current package version (alias: pkg/version, package-version) | (elle/version) |
io
| Function | Description | Example |
|---|---|---|
| (describe value) | Return a string describing a value's type and content. | (describe (list 1 2 3)) #=> "<list (3 elements)>" |
| (io/backend kind) | Create an I/O backend. :sync for synchronous, :async for asynchronous. | (io/backend :sync) (io/backend :async) |
| (io/cancel backend id) | Cancel a pending async I/O operation by submission ID. Returns nil. | (io/cancel backend id) |
| (io/execute backend request) | Execute an I/O request on a backend. Blocking. | (io/execute backend request) |
| (io/reap backend) | Non-blocking poll for async I/O completions. Returns array of completion structs. | (io/reap backend) |
| (io/submit backend request) | Submit an I/O request to an async backend. Returns submission ID. | (io/submit backend request) |
| (io/wait backend timeout-ms) | Wait for async I/O completions. timeout-ms: negative=forever, 0=poll, positive=ms. Returns array of completion structs. | (io/wait backend 1000) |
| (pp value) | Pretty-print a value with indentation. Returns the value. | (pp (list 1 2 (list 3 4))) |
list
| Function | Description | Example |
|---|---|---|
| (->array coll) | Convert any sequence to an immutable array. Lists, @arrays, sets, strings (graphemes), and bytes (integers) are supported. | (->array (list 1 2 3)) #=> [1 2 3] (->array @[1 2]) #=> [1 2] (->array |3 1 2|) #=> [1 2 3] |
| (->list coll) | Convert any sequence to a list. Arrays, @arrays, sets, strings (graphemes), and bytes (integers) are supported. | (->list [1 2 3]) #=> (1 2 3) (->list @[1 2]) #=> (1 2) (->list |3 1 2|) #=> (1 2 3) |
| (append collection1 collection2) | Append two collections. For arrays: mutates first arg, returns it. For strings: returns new value. | (append @[1 2] @[3 4]) |
| (butlast list) | Get all elements of a list except the last | (butlast (list 1 2 3)) |
| (concat collections) | Concatenate one or more collections of the same type. Supports: list, array, @array, string, @string, bytes, @bytes, set, @set, struct, @struct. For sets, performs union. For structs, merges left-to-right (right wins on key conflict). Returns a new value. | (concat [1 2] [3 4]) #=> [1 2 3 4] |
| (cons car cdr) | Construct a cons cell with car and cdr | (cons 1 (cons 2 ())) |
| (drop count list) | Drop the first n elements of a list | (drop 2 (list 1 2 3 4)) |
| (first sequence) | Get the first element of a sequence (list, array, string). Returns nil for empty. | (first (list 1 2 3)) |
| (last list) | Get the last element of a list | (last (list 1 2 3)) |
| (length collection) | Get the length of a collection (list, string, array, table, struct, symbol, or keyword) | (length (list 1 2 3)) |
| (list elements) | Create a list from arguments | (list 1 2 3) |
| (rest sequence) | Get the rest of a sequence. Returns type-preserving empty for empty input. | (rest (list 1 2 3)) |
| (reverse sequence) | Reverse a sequence (list, array, string). Returns same type. | (reverse (list 1 2 3)) |
| (take count list) | Take the first n elements of a list | (take 2 (list 1 2 3 4)) |
logic
| Function | Description | Example |
|---|---|---|
| (not x) | Logical NOT operation | (not true) |
| (xor) | Logical XOR operation | (xor true false) |
parameter
| Function | Description | Example |
|---|---|---|
| (parameter default) | Create a new dynamic parameter with a default value. (alias: make-parameter) | (def p (parameter 42)) (p) #=> 42 |
path
| Function | Description | Example |
|---|---|---|
| (path/absolute path) | Compute absolute path (does not require path to exist) | (path/absolute "src") |
| (path/absolute? path) | True if path is absolute | (path/absolute? "/foo") |
| (path/canonicalize path) | Resolve path through filesystem (symlinks resolved, must exist) | (path/canonicalize ".") |
| (path/components path) | Split path into list of components | (path/components "/a/b/c") |
| (path/cwd) | Get current working directory | (path/cwd) |
| (path/dir? path) | Check if path is a directory (alias: directory?, file/directory?) | (path/dir? "/home") |
| (path/exists? path) | Check if path exists (alias: file-exists?, file/exists?) | (path/exists? "data.txt") |
| (path/extension path) | Get file extension without dot (nil if none) | (path/extension "data.txt") |
| (path/file? path) | Check if path is a regular file (alias: file?, file/file?) | (path/file? "data.txt") |
| (path/filename path) | Get file name (last component, nil if none) | (path/filename "/home/user/data.txt") |
| (path/join components) | Join path components | (path/join "a" "b" "c") |
| (path/normalize path) | Lexical path normalization (resolve . and ..) | (path/normalize "./a/../b") |
| (path/parent path) | Get parent directory (nil if none) | (path/parent "/home/user/data.txt") |
| (path/relative target base) | Compute relative path from base to target (nil if impossible) | (path/relative "/foo/bar/baz" "/foo/bar") |
| (path/relative? path) | True if path is relative | (path/relative? "foo") |
| (path/stem path) | Get file stem (filename without extension, nil if none) | (path/stem "archive.tar.gz") |
| (path/with-extension path ext) | Replace file extension (empty string removes it) | (path/with-extension "foo.txt" "rs") |
port
| Function | Description | Example |
|---|---|---|
| (port/close port) | Close a port. Idempotent. Yields to cancel pending I/O before closing the fd. | (port/close p) |
| (port/flush port) | Flush port's write buffer. (alias: stream/flush) | (port/flush (port/stdout)) |
| (port/open path mode) | Open a file as a text (UTF-8) port. Accepts optional :timeout ms keyword. | (port/open "data.txt" :read) (port/open "fifo" :read :timeout 5000) |
| (port/open-bytes path mode) | Open a file as a binary port. Accepts optional :timeout ms keyword. | (port/open-bytes "data.bin" :read) (port/open-bytes "fifo" :read :timeout 5000) |
| (port/open? port) | Check if a port is open. Signals :type-error on non-port. | (port/open? (port/stdout)) #=> true |
| (port/path port) | Return the path or address the port was opened on, or nil for stdio ports. | (port/path (tcp/listen "127.0.0.1" 0)) |
| (port/read port n) | Read up to n bytes from port. Returns bytes or nil (EOF). (alias: stream/read) | (port/read (port/open "file.txt" :read) 1024) |
| (port/read-all port) | Read everything remaining from port. (alias: port/read-all) | (port/read-all (port/open "file.txt" :read)) |
| (port/read-line port) | Read one line from port. Returns string or nil (EOF). (alias: port/read-line) | (port/read-line (port/open "file.txt" :read)) |
| (port/seek port offset) | Seek to a byte offset in a file port. Returns new absolute position. Syntax: (port/seek port offset [:from :start|:current|:end]) Default :from is :start (SEEK_SET). Discards the read buffer on seek. | (port/seek p 0) (port/seek p 0 :from :start) (port/seek p -1 :from :end) |
| (port/set-options port) | Set port options. Currently: :timeout ms (nil clears). | (port/set-options p :timeout 5000) |
| (port/stderr) | Return a port for standard error. | (port/stderr) |
| (port/stdin) | Return a port for standard input. | (port/stdin) |
| (port/stdout) | Return a port for standard output. | (port/stdout) |
| (port/tell port) | Return current logical byte position in a file port. Accounts for per-fd read buffering: position = kernel_offset - buffer.len(). | (port/tell p) |
| (port/write port data) | Write data to port. Returns bytes written. (alias: stream/write) | (port/write (port/stdout) "hello") |
predicate
| Function | Description | Example |
|---|---|---|
| (array? value) | Check if value is an array (immutable or mutable indexed sequence). (alias: tuple?) | (array? [1 2 3]) #=> true (array? @[1 2 3]) #=> true (array? 42) #=> false |
| (boolean? value) | Check if value is a boolean. (alias: bool?) | (boolean? true) #=> true (boolean? 42) #=> false |
| (box? value) | Check if a value is a box. | (box? (box 1)) #=> true (box? 42) #=> false |
| (bytes? value) | Check if value is bytes (immutable or mutable binary data). | (bytes? (bytes 1 2 3)) #=> true (bytes? (@bytes 1 2 3)) #=> true (bytes? 42) #=> false |
| (closure? value) | Returns true if value is a bytecode closure | (closure? (fn (x) x)) |
| (coroutine? value) | Returns true if value is a coroutine (fiber-based) (alias: coro?) | (coroutine? (coro/new (fn () 42))) |
| (empty? collection) | Check if a collection is empty | (empty? (list)) |
| (float? value) | Check if value is a floating-point number. | (float? 3.14) #=> true (float? 42) #=> false |
| (immutable? value) | Check if value is immutable (cannot be modified in-place). | (immutable? [1 2 3]) #=> true (immutable? @[1 2 3]) #=> false |
| (inf? value) | Check if value is infinite. Returns false for non-numbers. (alias: infinite?) | (inf? (/ 1.0 0.0)) #=> true (inf? 1.0) #=> false (inf? 42) #=> false |
| (integer? value) | Check if value is an integer (full-range i64). (alias: int?) | (integer? 42) #=> true (integer? 3.14) #=> false |
| (io-backend? value) | Check if value is an I/O backend. | (io-backend? 42) #=> false |
| (io-request? value) | Check if value is an I/O request. | (io-request? 42) #=> false |
| (jit? value) | Returns true if closure has JIT-compiled code | (jit? (fn (x) x)) |
| (keyword? value) | Check if value is a keyword. | (keyword? :foo) #=> true (keyword? 42) #=> false |
| (list? value) | Check if value is a list (empty list or cons cell). | (list? (list 1 2)) #=> true (list? 42) #=> false |
| (mutable? value) | Check if value is mutable (can be modified in-place). | (mutable? @[1 2 3]) #=> true (mutable? [1 2 3]) #=> false |
| (nan? value) | Check if value is NaN (not a number). Returns false for non-numbers. | (nan? (/ 0.0 0.0)) #=> true (nan? 1.0) #=> false (nan? 42) #=> false |
| (neg? value) | Check if number is negative (less than zero). (alias: negative?) | (neg? -1) #=> true (neg? 0) #=> false (neg? 1) #=> false |
| (nil? value) | Check if value is nil. | (nil? nil) #=> true (nil? 42) #=> false |
| (nonempty? collection) | Check if a collection is non-empty (negation of empty?) | (nonempty? (list 1 2 3)) |
| (nonzero? value) | Check if value is numerically nonzero. | (nonzero? 1) #=> true (nonzero? 0) #=> false (nonzero? 0.0) #=> false |
| (number? value) | Check if value is a number. | (number? 42) #=> true (number? "hello") #=> false |
| (pair? value) | Check if value is a pair (cons cell). | (pair? (cons 1 2)) #=> true (pair? 42) #=> false |
| (parameter? value) | Check if value is a dynamic parameter. | (parameter? (make-parameter 0)) #=> true (parameter? 42) #=> false |
| (port? value) | Check if value is a port. | (port? (port/stdin)) #=> true |
| (pos? value) | Check if number is positive (greater than zero). (alias: positive?) | (pos? 1) #=> true (pos? 0) #=> false (pos? -1) #=> false |
| (ptr? value) | Check if value is a raw C pointer. (alias: pointer?) | (ptr? ptr) #=> true (ptr? 42) #=> false |
| (silent? value) | Returns true if closure is silent (does not suspend: no yield, debug, or polymorphic signal). False for non-closures. | (silent? (fn (x) x)) |
| (string? value) | Check if value is a string (immutable or mutable). | (string? "hello") #=> true (string? @"hello") #=> true (string? 42) #=> false |
| (struct? value) | Check if value is a struct (immutable or mutable key-value map). (alias: table?) | (struct? {:a 1}) #=> true (struct? @{:a 1}) #=> true (struct? 42) #=> false |
| (symbol? value) | Check if value is a symbol. | (symbol? 'foo) #=> true (symbol? 42) #=> false |
| (type-of value) | Get the type of a value as a keyword. (alias: type) | (type-of 42) #=> :integer (type-of "hello") #=> :string |
| (zero? value) | Check if value is numerically zero. | (zero? 0) #=> true (zero? 0.0) #=> true (zero? 1) #=> false |
ptr
| Function | Description | Example |
|---|---|---|
| (ptr/add pointer offset) | Offset a pointer by a byte count. Returns a raw pointer. Offset may be negative. | (ptr/add buf 16) |
| (ptr/diff pointer-a pointer-b) | Compute the signed byte distance between two pointers (a - b). | (ptr/diff p2 p1) |
| (ptr/from-int integer) | Construct a raw C pointer from an integer address. Returns nil if address is 0. | (ptr/from-int addr) |
| (ptr/to-int pointer) | Extract the raw address of a pointer as an integer. | (ptr/to-int buf) |
scheduler
| Function | Description | Example |
|---|---|---|
| (ev/sleep seconds) | Async sleep — yields to the scheduler for the specified duration in seconds | (ev/sleep 0.5) |
set
| Function | Description | Example |
|---|---|---|
| (@set) | Create a mutable set from elements (deduplicates, freezes mutable values) | (@set 1 2 3) |
| (add set value) | Add an element to a set. For immutable sets, returns a new set. For mutable sets, modifies in place. | (add (set 1 2) 3) #=> |1 2 3| |
| (difference set1 set2) | Compute the difference of two sets (both must be the same type) | (difference (set 1 2 3) (set 2)) #=> |1 3| |
| (intersection set1 set2) | Compute the intersection of two sets (both must be the same type) | (intersection (set 1 2) (set 2 3)) #=> |2| |
| (seq->set seq) | Convert any sequence to a set. Immutable inputs (list, tuple, string, bytes, set) → immutable set. Mutable inputs (array, buffer, blob, @set) → mutable set. Freezes mutable values on insertion. | (seq->set [1 2 3]) #=> |1 2 3| |
| (set) | Create an immutable set from elements (deduplicates, freezes mutable values) | (set 1 2 3) |
| (set->array set) | Convert a set to an array/tuple. Immutable set → tuple, mutable set → array. | (set->array (set 3 1 2)) #=> [1 2 3] |
| (set? value) | Check if value is a set (immutable or mutable). Use (type-of x) to distinguish. | (set? (set 1 2)) #=> true (set? 42) #=> false |
| (string-contains? string substring) | Deprecated: use has? instead. Check if a string contains a substring. | (string-contains? "hello world" "world") #=> true |
| (union set1 set2) | Compute the union of two sets (both must be the same type) | (union (set 1 2) (set 2 3)) #=> |1 2 3| |
special form
| Function | Description | Example |
|---|---|---|
| (and expr...) | Short-circuit logical AND. Returns the first falsy value, or the last value if all truthy. | (and (> x 0) (< x 100)) |
| (assign name value) | Mutate a var binding. Only works on names defined with var. | (var x 0) (assign x 42) |
| (begin expr...) | Sequence expressions. Does NOT create a scope — bindings leak into the enclosing scope. | (begin (def x 1) (def y 2) (+ x y)) |
| (block :name? body...) | Sequence expressions in a new lexical scope. Supports optional keyword name for break targeting. | (block :outer (if done (break :outer result)) (continue)) |
| (break :name? value) | Exit a named block with a value. Must be inside a block; cannot cross function boundaries. | (block :loop (break :loop 42)) |
| (cond (test body)...) | Multi-branch conditional. Tests clauses in order, evaluating the body of the first true test. | (cond ((< x 0) "negative") ((= x 0) "zero") (true "positive")) |
| (def pattern value) | Bind a value to an immutable name. Supports destructuring patterns including lists, arrays, and tables. | (def x 42) (def {:name n :age a} {:name "Alice" :age 30}) |
| (defmacro name (params...) body...) | Define a syntax macro. The macro function receives syntax objects and returns a syntax object. | (defmacro my-if (cond then else) (cond ((,cond) ,then) (true ,else))) |
| (doc name) | Display documentation for a named function or special form. Accepts a symbol or string — bare symbols are rewritten to strings by the analyzer. | (doc map) (doc "map") |
| (each (name list) body...) | Iterate over a list, binding each element to a name. | (each (x (list 1 2 3)) (display x)) |
| (eval expr env?) | Compile and execute an expression at runtime. The expression is a quoted datum that goes through the full compilation pipeline (expand, analyze, lower, emit, execute). An optional second argument provides an environment as a table or struct — its key-value pairs become let bindings around the expression. | (eval '(+ 1 2)) (eval '(+ x y) {:x 10 :y 20}) |
| (fn (params...) body...) | Create an anonymous function (lambda). Supports destructuring in parameters. | (fn (x y) (+ x y)) |
| (if condition then else?) | Conditional expression. Evaluates condition, then either the then-branch or the else-branch. | (if (> x 0) "positive" "non-positive") |
| (let ((name value) ...) body...) | Bind values to names in a new scope. Supports destructuring patterns. | (let ((x 1) (y 2)) (+ x y)) |
| (letrec ((name value) ...) body...) | Recursive let. Bindings can reference each other (for mutual recursion). | (letrec ((even? (fn (n) (if (= n 0) true (odd? (- n 1))))) (odd? (fn (n) (if (= n 0) false (even? (- n 1)))))) (even? 10)) |
| (match value (pattern body)...) | Pattern matching. Tests value against patterns in order, executing the first matching arm. | (match x (0 "zero") ((a . b) (+ a b)) (_ "other")) |
| (or expr...) | Short-circuit logical OR. Returns the first truthy value, or the last value if all falsy. | (or default-value (compute-value)) |
| (quote form) | Return the unevaluated form. Prevents evaluation of its argument. | (quote (+ 1 2)) # => (+ 1 2) |
| (splice expr) | Mark a value for spreading into a function call or data constructor. The short form is ;expr. Only works on arrays and tuples. Inside quasiquote, ,;expr is unquote-splicing. | (defn f [a b c] (+ a b c)) (def args @[1 2 3]) (f ;args) # => 6 |
| (var pattern value) | Bind a value to a mutable name. Supports destructuring. Use assign to mutate. | (var x 0) (assign x (+ x 1)) |
| (while condition body...) | Loop while condition is true. Returns nil. | (var i 0) (while (< i 10) (assign i (+ i 1))) |
| (yield value) | Yield a value from a coroutine/fiber. Suspends execution until resumed. | (fn () (yield 1) (yield 2) (yield 3)) |
syntax sugar
| Function | Description | Example |
|---|---|---|
| (-> value forms...) | Thread-first macro. Inserts value as first argument of each successive form. | (-> 5 (+ 3) ( 2)) # => ( (+ 5 3) 2) => 16 |
| (->> value forms...) | Thread-last macro. Inserts value as last argument of each successive form. | (->> 5 (- 10) ( 2)) # => ( (- 10 5) 2) => 10 |
| (defer body...) | Register cleanup to run when the enclosing scope exits. | (defer (close handle)) |
| (defn name (params...) body...) | Define a named function. Shorthand for (def name (fn (params) body...)). | (defn add (x y) (+ x y)) |
| (error value?) | Signal an error. The value can be anything; by convention a tuple [:kind "message"]. With no argument, signals nil. | (error) (error [:not-found "missing key"]) (error "something broke") |
| (ffi/defbind name lib-handle "c-name" return-type [arg-types...]) | Define a named wrapper for a C function via FFI. Looks up the symbol, creates a signature, and defines a function that calls it. | (ffi/defbind abs libc "abs" :int [:int]) |
| (let ((name value) ...) body...) | Sequential let. Each binding can reference previous bindings. Desugars to nested let. | (let ((x 1) (y (+ x 1))) (+ x y)) |
| (protect body cleanup...) | Execute body with cleanup. Cleanup runs whether body succeeds or fails. | (protect (read-file f) (close f)) |
| (try body (catch e handler)) | Error handling. Evaluates body; if an error is signaled, evaluates catch handler with the error value. | (try (/ 1 0) (catch e (display e))) |
| (unless condition body...) | Evaluate body when condition is false. Returns nil if true. | (unless (empty? lst) (first lst)) |
| (when condition body...) | Evaluate body when condition is true. Returns nil if false. | (when (> x 0) (display "positive")) |
| (with (name init) body...) | Bind a resource and ensure cleanup. Combines let + protect. | (with (f (open "file.txt")) (read-file f)) |
| (yield generator) | Delegate to a sub-coroutine, yielding all its values bidirectionally. | (defn gen () (yield (sub-gen))) |
sys
| Function | Description | Example |
|---|---|---|
| (subprocess/exec program args opts) | Spawn a subprocess. Returns {:pid int :stdin port|nil :stdout port|nil :stderr port|nil :process <process>} | (subprocess/exec "ls" ["-la"]) |
| (subprocess/kill handle signal) | Send a signal to a subprocess. signal is an integer or a keyword like :sigterm, :sigkill, :sighup, :sigint, :sigquit, :sigpipe, :sigalrm, :sigusr1, :sigusr2, :sigchld, :sigcont, :sigstop, :sigtstp, :sigttin, :sigttou, :sigwinch (default: :sigterm). | (subprocess/kill proc :sigterm) |
| (subprocess/pid handle) | Return the OS process ID of a subprocess. | (subprocess/pid proc) |
| (subprocess/wait handle) | Wait for a subprocess to exit. Returns exit code (0 = success). | (subprocess/wait proc) |
| (sys/args) | Return command-line arguments as a list (excluding interpreter and script path) | (sys/args) |
| (sys/argv) | Return the full argv as a list: script name as element 0 followed by all user args. Element 0 is "-" for stdin or the script path for a file. Returns an empty list in REPL mode. | (sys/argv) |
| (sys/env name) | Return the process environment as a struct with string keys and string values, or look up a single variable by name. Non-UTF-8 entries are silently skipped. | (sys/env) ; or (sys/env "HOME") |
| (sys/exit code) | Exit the process with an optional exit code (0-255) (alias: exit, os/exit) | (sys/exit 0) |
| (sys/halt value) | Halt the VM gracefully, returning a value to the host (alias: halt, os/halt) | (sys/halt 42) |
| (sys/join thread-handle) | Wait for a thread to complete and return its result (alias: join, os/join) | (sys/join thread-handle) |
| (sys/resolve hostname) | Resolve a hostname to IP addresses via the system resolver (getaddrinfo). Returns an array of IP address strings. | (sys/resolve "localhost") |
| (sys/spawn closure) | Spawn a new thread that executes a closure with captured immutable values (alias: spawn, os/spawn) | (sys/spawn (fn [] (+ 1 2))) |
| (sys/thread-id) | Return the ID of the current thread (alias: current-thread-id, os/thread-id) | (sys/thread-id) |
tcp
| Function | Description | Example |
|---|---|---|
| (tcp/accept listener) | Accept a connection on a TCP listener. Returns a stream port. | (tcp/accept listener) |
| (tcp/connect addr port) | Connect to a TCP address. Returns a stream port. | (tcp/connect "127.0.0.1" 8080) |
| (tcp/listen addr port) | Bind and listen on a TCP address. Returns a listener port. | (tcp/listen "127.0.0.1" 8080) |
| (tcp/shutdown port how) | Shutdown a TCP stream. how: :read, :write, or :read-write. | (tcp/shutdown conn :write) |
traits
| Function | Description | Example |
|---|---|---|
| (traits value) | Return the trait table attached to a value, or nil if none. Usable as boolean: (if (traits v) ...) checks for presence. | (traits (with-traits [1 2 3] {:Seq {:first (fn (v) (get v 0))}})) |
| (with-traits value table) | Attach a trait table to a value. Returns a new value with the same data and the given trait table. The table must be an immutable struct. | (with-traits [1 2 3] {:Seq {:first (fn (v) (get v 0))}}) |
types
| Function | Description | Example |
|---|---|---|
| (fn? x) | Returns true if value is callable (closure or native function). | (fn? +) #=> true (fn? (fn [x] x)) #=> true (fn? 42) #=> false |
| (native-fn? x) | Returns true if value is a native (built-in) function. (alias: native?, primitive?) | (native-fn? +) #=> true (native-fn? (fn [x] x)) #=> false |
udp
| Function | Description | Example |
|---|---|---|
| (udp/bind addr port) | Bind a UDP socket. Returns a UDP port. | (udp/bind "0.0.0.0" 9000) |
| (udp/recv-from socket count) | Receive data from a UDP socket. Returns {:data :addr :port}. | (udp/recv-from sock 1024) |
| (udp/send-to socket data addr port) | Send data to a remote address via UDP. Returns bytes sent. | (udp/send-to sock "hello" "127.0.0.1" 9000) |
unix
| Function | Description | Example |
|---|---|---|
| (unix/accept listener) | Accept a connection on a Unix listener. Returns a stream port. | (unix/accept listener) |
| (unix/connect path) | Connect to a Unix domain socket. Returns a stream port. | (unix/connect "/tmp/my.sock") |
| (unix/listen path) | Listen on a Unix domain socket. Returns a listener port. | (unix/listen "/tmp/my.sock") |
| (unix/shutdown port how) | Shutdown a Unix stream. how: :read, :write, or :read-write. | (unix/shutdown conn :write) |