/ Specification
Playground Docs Performance GitHub
Chapter 12

Standard Library

Lattice ships with over 150 built-in functions and type methods organized into categories. All built-ins are available without imports. For complete function signatures and detailed usage, see the full API documentation.

Core Functions

Core functions provide essential operations: output, type introspection, assertions, and value conversion.

FunctionDescription
print(...args)Output values to stdout
typeof(value)Return the type name as a string
phase_of(value)Return the phase tag as a string
assert(condition, msg?)Abort if condition is false
error(value)Create an error result map ({"tag": "err", "value": ...})
is_error(value)Check if value is an error result
require(path)Load a module at runtime
sleep(ms)Pause execution for milliseconds
time()Current Unix timestamp in seconds
len(value)Return length of string, array, map, or set
input(prompt)Read a line from stdin
version()Return Lattice version string

Phase Transition Functions

FunctionDescription
freeze(value)Transition to crystal phase
thaw(value)Transition to fluid phase
clone(value)Deep copy a value
anneal(value) |v| { ... }Thaw, transform, re-freeze
sublimate(value)Shallow freeze (structure locked, elements mutable)
crystallize(value) { ... }Deep freeze with scoped contracts (tree-walk only)
Note Phase transition functions (freeze, thaw, clone, anneal, sublimate, crystallize) and phase operators (bond, react, seed) are language constructs compiled to dedicated bytecode opcodes — they are not runtime native functions.

Phase System Builtins

FunctionDescription
track(value)Enable temporal tracking on a value
phases(value)Get phase transition history
rewind(value)Revert to previous phase state
seed(value, fn)Register a deferred crystallization contract
unseed(value)Remove seed contract
grow(value)Evaluate seed contracts on a value
bond(a, b, strategy)Link two values with a phase strategy ("mirror", "inverse", "gate")
unbond(a, b)Remove phase bond
react(value, fn)Register a callback for phase changes: |phase, value|
unreact(value)Remove reaction callback
pressurize(value, mode)Apply structural pressure ("no_grow", "no_shrink", "no_resize", "read_heavy")
depressurize(value)Remove structural pressure
pressure_of(value)Query current pressure mode

Result Helpers (lib/fn.lat)

The following helpers are defined in the standard library file lib/fn.lat and must be imported before use:

FunctionDescription
ok(value)Create a success result map ({"tag": "ok", "value": ...})
err(value)Create an error result map ({"tag": "err", "value": ...})
is_ok(result)Check if result has "ok" tag
is_err(result)Check if result has "err" tag

Type Constructors

ConstructorDescription
Map::new()Create an empty map
Set::new()Create an empty set
Channel::new()Create a new channel
Set::from(array)Create a set from an array

Type Conversion

FunctionDescription
to_int(value)Convert to integer (or nil on failure)
to_float(value)Convert to float
to_string(value)Convert to string
parse_int(str)Parse string to integer
parse_float(str)Parse string to float
ord(char)Character to integer code point
chr(code)Integer code point to character
repr(value)Debug representation as string

Math

A comprehensive math library including trigonometry, logarithms, rounding, random numbers, and constants.

FunctionDescription
abs(x), ceil(x), floor(x), round(x)Rounding
sin(x), cos(x), tan(x)Trigonometry
asin(x), acos(x), atan(x), atan2(y, x)Inverse trigonometry
sinh(x), cosh(x), tanh(x)Hyperbolic
sqrt(x), pow(x, y), exp(x)Powers and exponentials
log(x), log2(x), log10(x)Logarithms
min(a, b), max(a, b), clamp(x, lo, hi)Bounds
sign(x), lerp(a, b, t)Sign and interpolation
gcd(a, b), lcm(a, b)Number theory
is_nan(x), is_inf(x)Special value checks
random(), random_int(lo, hi)Random numbers
math_pi(), math_e()Constants (pi and e)

String Methods

21 methods for string manipulation:

MethodDescription
.len()String length
.to_upper(), .to_lower()Case conversion
.trim(), .trim_start(), .trim_end()Whitespace trimming
.split(sep)Split into array
.contains(sub)Substring check
.starts_with(s), .ends_with(s)Prefix/suffix check
.replace(old, new)String replacement
.substring(start, end)Substring extraction
.index_of(sub)Find substring position
.chars()Split into character array
.bytes()Split into byte value array
.reverse()Reverse string
.repeat(n)Repeat string n times
.pad_left(n, ch)Pad to length n on the left
.pad_right(n, ch)Pad to length n on the right
.count(sub)Count occurrences of substring
.is_empty()Check if string is empty

Array Methods

35+ methods for array operations including functional programming patterns:

MethodDescription
.len()Array length
.push(val)Append element (mutates)
.pop()Remove and return last element
.insert(idx, val)Insert element at index
.remove_at(idx)Remove element at index
.map(fn)Transform each element
.filter(fn)Keep elements matching predicate
.reduce(fn, init)Fold into single value
.each(fn)Iterate with side effects
.for_each(fn)Iterate with side effects (alias)
.find(fn)First element matching predicate
.any(fn)True if any element matches predicate
.all(fn)True if all elements match predicate
.sort()Sort in ascending order
.sort_by(fn)Sort with comparator function
.reverse()Reverse array
.contains(val)Check membership
.flat_map(fn)Map and flatten
.flatten()Flatten nested arrays
.join(sep)Join into string
.slice(start, end)Sub-array extraction
.take(n)First n elements
.drop(n)All elements after first n
.chunk(size)Split into sub-arrays of given size
.zip(other)Pair elements from two arrays
.enumerate()Pair each element with its index
.unique()Remove duplicates
.group_by(fn)Group elements by key function
.sum()Sum all numeric elements
.first(), .last()First or last element

Map Methods

MethodDescription
.get(key)Get value by key
.set(key, value)Set key-value pair
.has(key)Check if key exists
.contains(key)Check if key exists (alias for .has())
.keys()Array of keys
.values()Array of values
.entries()Array of [key, value] pairs
.len()Number of entries
.merge(other)Merge two maps
.for_each(fn)Iterate with callback |key, value|

Set Methods

MethodDescription
.has(val)Check membership
.len()Set size
.to_array()Convert to array
.union(other)Set union
.intersection(other)Set intersection
.difference(other)Set difference
.is_subset(other)Check if subset of other
.is_superset(other)Check if superset of other

Other Categories

The standard library also includes functions for:

CategoryFunctionsDescription
JSONjson_parse, json_stringifyJSON serialization
CSVcsv_parse, csv_stringifyCSV serialization
Regexregex_match, regex_find_all, regex_replaceRegular expressions
File I/Oread_file, write_file, file_exists, etc.19 filesystem functions
Pathpath_join, path_dir, path_ext, path_basePath utilities
Networkingtcp_connect, tls_connect, etc.15 TCP/TLS functions
HTTPhttp_get, http_post, http_requestHTTP client
TOMLtoml_parse, toml_stringifyTOML serialization
YAMLyaml_parse, yaml_stringifyYAML serialization
Cryptosha256, md5, base64_encode, base64_decodeHashing and encoding
Date/Timetime(), sleep, time_format, time_parseTimestamps and formatting
Processexec, shell, env, env_set, env_keys, exitSystem process control
Formattingformatprintf-style string formatting
URLurl_encode, url_decodeURL encoding/decoding
Functionalpipe, compose, identityFunction composition
Introspectionstruct_name, struct_fields, struct_to_mapStruct reflection
Note For complete function signatures with parameter types and return types, see the full API documentation.

Channel Methods

MethodDescription
.send(value)Send crystal value into channel
.recv()Receive value from channel (blocking)
.close()Close the channel