Rayforce ← Back to home
GitHub

Functions Reference

Complete reference for all Rayfall built-in functions. Each entry shows the function name, arity type (unary/binary/variadic), flags, description, and example usage.

Legend: Functions marked atomic auto-map element-wise over vectors. Functions marked aggr reduce vectors to scalars. Functions marked special receive unevaluated arguments.

Arithmetic

All arithmetic operators are atomic — they auto-map over vectors and broadcast scalars.

FunctionTypeDescriptionExample
+binaryAddition(+ 3 4)7
-binarySubtraction(- 10 3)7
*binaryMultiplication(* 3 4)12
/binaryInteger division (floor)(/ 7 2)3
%binaryModulo(% 7 3)1
divbinaryFloat division (always f64)(div 7 2)3.5
negunaryNegate(neg 5)-5
roundunaryRound to nearest integer(round 3.7)4.0
floorunaryFloor (round down)(floor 3.7)3.0
ceilunaryCeiling (round up)(ceil 3.2)4.0
xbarbinaryRound down to nearest multiple (bucketing)(xbar [3 7 12] 5)[0 5 10]

Vector examples:

(+ [1 2 3] [10 20 30])   ; [11 22 33]
(* [1 2 3] 10)            ; [10 20 30]  scalar broadcast
(neg [1 -2 3])             ; [-1 2 -3]
(xbar [3 15 27] 10)      ; [0 10 20]

Comparison

All comparison operators are atomic and return boolean results.

FunctionTypeDescriptionExample
>binaryGreater than(> 5 3)true
<binaryLess than(< 3 5)true
>=binaryGreater than or equal(>= 5 5)true
<=binaryLess than or equal(<= 3 5)true
==binaryEqual(== 3 3)true
!=binaryNot equal(!= 3 4)true
withinbinaryCheck which vector elements fall within a range(within [1 5 10] [3 7])[false true false]

Logic

FunctionTypeDescriptionExample
andbinaryLogical AND(and true false)false
orbinaryLogical OR(or true false)true
notunaryLogical NOT(not true)false

Aggregation

Aggregation functions are marked aggr and reduce vectors to scalar values. Used in select with by: for group-by aggregation.

FunctionTypeDescriptionExample
sumunary, aggrSum of all elements(sum [1 2 3])6
countunary, aggrCount of elements(count [1 2 3])3
avgunary, aggrArithmetic mean(avg [1 2 3])2.0
minunary, aggrMinimum value(min [3 1 2])1
maxunary, aggrMaximum value(max [3 1 2])3
medunary, aggrMedian value(med [1 3 2])2
devunary, aggrStandard deviation(dev [1 2 3])0.816...
firstunaryFirst element of vector(first [10 20 30])10
lastunaryLast element of vector(last [10 20 30])30
; Group-by aggregation example
(select {from: trades
         by:   {sym: sym}
         cols: {hi: (max price) lo: (min price) n: (count price)}})

Higher-Order Functions

Functions that take other functions as arguments.

FunctionTypeDescriptionExample
mapvariadicApply function to each element(map (fn [x] (* x 2)) [1 2 3])[2 4 6]
pmapvariadicParallel map (multi-threaded)(pmap (fn [x] (* x x)) [1 2 3])[1 4 9]
filterbinaryKeep elements where boolean mask is true(filter [1 2 3 4] (> [1 2 3 4] 2))[3 4]
foldvariadicReduce with function and initial value(fold + 0 [1 2 3])6
fold-leftvariadicLeft-associative fold(fold-left - 10 [1 2 3])4
fold-rightvariadicRight-associative fold(fold-right - 10 [1 2 3])-8
scanvariadicRunning fold (returns all intermediate results)(scan + (enlist 1 2 3))[1 3 6]
scan-leftvariadicLeft-to-right running fold(scan-left + (enlist 1 2 3))[1 3 6]
scan-rightvariadicRight-to-left running fold(scan-right + (enlist 1 2 3))[6 5 3]
applyvariadicZip-apply function pairwise over two lists(apply + (enlist 1 2) (enlist 3 4))[4 6]
map-leftvariadicMap with left argument fixed(map-left + 10 [1 2 3])[11 12 13]
map-rightvariadicMap with right argument fixed(map-right - [10 20 30] 5)[5 15 25]

Collection Operations

Operations on vectors as collections.

FunctionTypeDescriptionExample
distinctunaryRemove duplicates(distinct [1 2 2 3])[1 2 3]
inbinaryMembership test (element in vector)(in 2 [1 2 3])true
exceptbinarySet difference(except [1 2 3] [2])[1 3]
unionbinarySet union(union [1 2] [2 3])[1 2 3]
sectbinarySet intersection(sect [1 2 3] [2 3 4])[2 3]
takebinaryTake first/last N elements(take [10 20 30] 2)[10 20]
atbinaryIndex into vector(at [10 20 30] 1)20
findbinaryFind index of value(find [10 20 30] 20)1
reverseunaryReverse order(reverse [1 2 3])[3 2 1]
tilunaryRange [0..n)(til 5)[0 1 2 3 4]
enlistvariadicWrap value(s) in a vector(enlist 1 2 3)[1 2 3]
concatbinaryConcatenate two vectors(concat [1 2] [3 4])[1 2 3 4]
razeunaryFlatten a list of vectors into one(raze (list [1 2] [3 4]))[1 2 3 4]
whereunaryIndices where boolean vector is true(where [true false true])[0 2]
groupunaryGroup indices by value(group [A B A]) → dict of groups
diverseunaryCheck if all elements are unique(diverse [1 2 3])true
randbinaryN random values from range or vector(rand 3 100) → 3 random ints 0..99
binbinaryBinary search (left boundary)(bin [10 20 30] 25)1
binrbinaryBinary search (right boundary)(binr [10 20 30] 25)2
unifybinaryMerge two tables/dicts, second takes precedence(unify d1 d2)

Sorting & Ordering

FunctionTypeDescriptionExample
ascunarySort ascending(asc [3 1 2])[1 2 3]
descunarySort descending(desc [3 1 2])[3 2 1]
iascunaryIndices that would sort ascending(iasc [30 10 20])[1 2 0]
idescunaryIndices that would sort descending(idesc [30 10 20])[0 2 1]
rankunaryRank of each element(rank [30 10 20])[2 0 1]
xascbinarySort table ascending by column(s)(xasc 'price trades)
xdescbinarySort table descending by column(s)(xdesc 'price trades)
xrankbinaryAssign rank buckets (quantiles)(xrank 4 [10 20 30 40])[0 1 2 3]

Table Operations

FunctionTypeDescriptionExample
listvariadicCreate a list from vectors(list [1 2] [A B])
tablebinaryCreate table from column names + list of vectors(table [x y] (list [1 2] [A B]))
keyunaryGet column names (table) or keys (dict)(key trades)[sym price size]
valueunaryGet column data (table) or values (dict)(value trades)
dictbinaryCreate dictionary from keys and values(dict [a b] [1 2])
getbinaryLookup key in dict/table(get d 'a)1
removebinaryRemove key from dict(remove d 'a)
rowbinaryExtract single row from table as dict(row trades 0)
metaunaryGet metadata (column types, lengths)(meta trades)
altervariadic, specialIn-place mutation of table column(alter trades 'price (* price 1.1))
delvariadic, specialDelete columns or rows from table(del trades 'temp_col)
modifyvariadicFunctional table update (returns new table)(modify trades 'price (fn [p] (* p 1.1)))

Query Operations

These are special forms that bridge to the Rayforce DAG executor.

FunctionTypeDescription
selectvariadic, specialQuery table with optional filter, projection, grouping, and aggregation
updatevariadic, specialAdd or modify columns in a table
insertvariadic, specialAppend a row to a table, append to a vector/list, or insert at position(s)
upsertvariadic, specialInsert or update rows (by key)
; Select with filter and projection
(select {from: trades
         where: (> price 100)
         cols: {sym: sym notional: (* price size)}})

; Group-by with multiple aggregates
(select {from: trades
         by:   {sym: sym}
         cols: {vwap: (/ (sum (* price size)) (sum size))
                count: (count price)}})

; Update: add a column
(update {from: trades
          cols: {notional: (* price size)}})

insert overloads on arity. With two arguments it appends; with three arguments it inserts at a position (or positions) given by the second argument. The first argument is a quoted symbol for in-place mutation, e.g. 'v, or any expression that evaluates to a table/vector/list.

; Append a row to a table
(insert 'trades (list 'AAPL 150.0 100))

; Vector / list operations
(def v (til 5))               ; [0 1 2 3 4]
(insert 'v 99)                  ; append:    [0 1 2 3 4 99]
(insert 'v 0 -1)                ; head:      [-1 0 1 2 3 4 99]
(insert 'v 3 [100 200])         ; splice:    [-1 0 1 100 200 2 3 4 99]
(insert 'v [0 3] 77)             ; broadcast 77 at pre-positions 0 and 3
(insert 'v [1 3] [10 30])         ; parallel: 10 at pos 1, 30 at pos 3

Indices are pre-insertion positions in [0, count]; idx == count is equivalent to append. Vector positional inserts of a same-typed vector splice that vector in. List positional inserts always add the value as a single slot — use concat to splice. Multi-insert is stable on duplicate indices, preserving input order. Typed-null atoms (0Nl, 0Nf, …) carry their null flag through — the inserted slot is marked null, not zero.

Joins

Rayforce supports four join types, all with time-series-aware semantics.

FunctionTypeDescription
left-joinvariadicLeft join on matching columns. Unmatched rows filled with nulls.
inner-joinvariadicInner join — only matching rows.
window-joinvariadic, specialJoin with time window constraint. Match rows within a time range.
asof-joinvariadicAs-of join — match the most recent preceding value.
; Left join two tables on the sym column
(left-join trades quotes 'sym)

; Inner join
(inner-join orders products 'product_id)

; Window join: match trades to quotes within 1-second window
(window-join {left: trades  right: quotes
              on: [sym]  window: [-1000 0]
              cols: {avg_bid: (avg bid)}})

; As-of join: find most recent quote for each trade
(asof-join trades quotes 'sym)

Pivot & Window

FunctionTypeDescriptionExample
pivotvariadicPivot table — reshape long to wide format(pivot trades 'sym 'date 'price)
xbarbinary, atomicBucket values (time bucketing for OHLC bars)(xbar [3 7 12] 5)[0 5 10]
xrankbinaryAssign N rank buckets (quantile ranking)(xrank 4 [10 20 30 40])
; OHLC bars: bucket trades by 5-minute intervals
(select {from: trades
         by:   {sym: sym  bucket: (xbar time 300000)}
         cols: {open: (first price)
                high: (max price)
                low:  (min price)
                close: (last price)
                vol:  (sum size)}})

String Operations

FunctionTypeDescriptionExample
splitbinarySplit string by delimiter(split "a,b,c" ",")["a" "b" "c"]
likebinaryGlob pattern match: * any, ? one, [abc]/[a-z]/[!abc] char class(like "hello" "hel*")true
concatbinaryConcatenate two strings or vectors(concat "hello" " world")"hello world"
formatvariadicFormat values as string (% is placeholder)(format "x=%" 42)"x=42"
Note: The executor supports additional string opcodes (STRLEN, UPPER, LOWER, TRIM, SUBSTR, REPLACE, CONCAT) at the DAG level. All string transformations propagate nulls: null input rows produce null output rows.

Date & Time

FunctionTypeDescriptionExample
dateunaryCurrent date or extract date from timestamp(date 0) → today's date
timeunaryCurrent time or extract time from timestamp(time 0) → current time
timestampunaryCurrent timestamp (nanosecond precision)(timestamp 0)

Calendar/Clock Field Extraction

Unary functions that pull a single calendar or clock field out of a DATE / TIME / TIMESTAMP atom or vector. Null input rows propagate to null output rows (the null sentinel bit pattern is not decoded as a bogus year / second). The same set of fields is reachable via dotted access on a temporal value (e.g. ts.yyyy — see Dotted Namespaces).

FunctionRangeExample
yyyyyear(yyyy 2024.03.15)2024
mm1..12(mm 2024.03.15)3
dd1..31(dd 2024.03.15)15
hh0..23(hh 12:34:56)12
minute0..59(minute 12:34:56)34
ss0..59(ss 12:34:56)56
dow1..7 (Mon=1)(dow 2024.03.15)5
doy1..366(doy 2024.03.15)75

mm is unambiguously MONTH; the minute spelling stays long-form because a two-letter token can't serve both meanings in a uniform dotted walk. Two dotted-only truncations exist: .date drops the time-of-day component (keeps the day), and .time drops the date component (keeps the microseconds within the day).

Cross-temporal comparisons are supported: dates, times, and timestamps are all converted to nanoseconds internally for comparison operations.

Type Operations

FunctionTypeDescriptionExample
typeunaryGet type name of a value(type 42)i64
asbinaryCast value to another type(as 'i64 "42")42
nil?unaryTest if value is null(nil? x)
rcunaryReference count of an object(rc x)1
guidunaryGenerate N GUIDs (0 for one)(guid 0)

I/O & File Operations

FunctionTypeDescriptionExample
printlnvariadicPrint values with newline(println "hello" 42)
printunaryPrint value without newline(print "hello")
showvariadicPretty-print a value (tables formatted)(show trades)
formatvariadicFormat value to string (% is placeholder)(format "val=%" 42)"val=42"
.csv.readvariadicLoad CSV file into table(.csv.read "data.csv")
.csv.writevariadicWrite table to CSV file(.csv.write trades "out.csv")
readunaryRead file contents as string(read "file.txt")
writebinaryWrite string to file(write "file.txt" "content")
loadunaryLoad and evaluate a Rayfall script(load "lib.rfl")

Control Flow

FunctionTypeDescriptionExample
setbinary, specialBind value to global variable(set x 42)
letbinary, specialBind value to local variable(let y (+ x 1))
ifvariadic, specialConditional (if/then/else)(if (> x 0) "pos" "neg")
dovariadic, specialSequential execution, returns last(do (set x 1) (set y 2) (+ x y))
fnvariadic, specialCreate lambda function(fn [x] (* x x))
trybinary, specialError handling (expr handler)(try (/ 1 0) (fn [e] 0))
raiseunaryThrow an error(raise "bad input")
returnunaryEarly return from function(return 42)
quotevariadic, specialReturn argument unevaluated(quote (+ 1 2))(+ 1 2)
resolvevariadic, specialResolve a symbol in current scope(resolve 'x)

System & Utility

FunctionTypeDescriptionExample
evalunaryEvaluate a parsed expression(eval (parse "(+ 1 2)"))3
parseunaryParse string into Rayfall expression(parse "(+ 1 2)")
.sys.gcvariadicTrigger garbage collection, returns 0(.sys.gc)
.sys.execunaryExecute shell command, return exit code(.sys.exec "ls -la")
.os.getenvunaryGet environment variable(.os.getenv "HOME")
.os.setenvbinarySet environment variable(.os.setenv "KEY" "value")
exitunaryExit with status code(exit 0)
timeitvariadic, specialBenchmark an expression(timeit (sum (til 1000000)))
timerunaryHigh-resolution monotonic nanosecond clock(timer 0)
argsunaryCommand-line arguments(args 0)
envunaryList all global environment bindings(env 0)
.sys.buildvariadicBuild metadata: version + build-date(.sys.build)
.sys.memvariadicMemory allocator statistics (alloc/peak/slab)(.sys.mem)
.sys.infovariadicSystem information (cores, page size, memory)(.sys.info)

Serialization & Storage

FunctionTypeDescriptionExample
serunarySerialize value to binary format(ser [1 2 3])
deunaryDeserialize from binary format(de bytes)
.db.splayed.setvariadicSave table as splayed columns to directory(.db.splayed.set "db/trades" trades)
.db.splayed.getvariadicLoad splayed table from directory(.db.splayed.get "db/trades")
.db.parted.getvariadicLoad partitioned table by name from root directory(.db.parted.get "db" 'trades)

EAV (Entity-Attribute-Value)

Built-in support for triple stores. The EAV table has three columns: e (entity, i64), a (attribute, sym), v (value, i64).

FunctionTypeDescriptionExample
datomsnullaryCreate empty EAV table(datoms)
assert-factvariadicAppend triple to datoms(assert-fact db 1 'name 100)
retract-factvariadicRemove triple from datoms(retract-fact db 1 'name 100)
scan-eavbinaryQuery EAV by attribute(scan-eav db 'name)
pullbinaryEntity-centric retrieval (returns dict)(pull db 1){name:100 age:30}
sym-nameunaryConvert sym intern ID to symbol string(sym-name 0)
; Build an EAV store
(set db (datoms))
(set db (assert-fact db 1 'name 100))
(set db (assert-fact db 1 'age 30))
(pull db 1)              ; {name:100 age:30}
(scan-eav db 'name)     ; table of (e, v) pairs where a='name

Table Set Operations

FunctionTypeDescriptionExample
union-allbinaryConcatenate two tables (all rows)(union-all t1 t2)
table-distinctunaryRemove duplicate rows from table(table-distinct t)
antijoinvariadicAnti-semi-join: rows in left not in right(antijoin t1 t2 [x])
; Table concatenation and deduplication
(set t1 (table [x] (list [1 2])))
(set t2 (table [x] (list [2 3])))
(union-all t1 t2)          ; 4 rows: 1 2 2 3
(table-distinct (union-all t1 t2))  ; 3 rows: 1 2 3
(antijoin t1 t2 [x])     ; 1 row: 1

Datalog

Datalog rules and queries integrate with the EAV store. Rules use the (?entity :attribute ?value) pattern to match triples.

FunctionTypeDescriptionExample
rulevariadic, specialDefine Datalog rule(rule (path ?x ?y) (?x :edge ?y))
queryvariadic, specialCompile and execute Datalog query(query db (find ?x ?y) (where (path ?x ?y)))
notspecial (in Datalog WHERE)Stratified negation in WHERE clause(not (?y :edge 3))
; Define rules and query
(rule (path ?x ?y) (?x :edge ?y))
(rule (path ?x ?z) (?x :edge ?y) (path ?y ?z))

(set db (datoms))
(set db (assert-fact db 1 'edge 2))
(set db (assert-fact db 2 'edge 3))
(query db (find ?x ?y) (where (path ?x ?y)))
; returns table: (1,2) (1,3) (2,3)

Datalog Program API

Low-level API for building and evaluating Datalog programs directly, bypassing the EAV store.

FunctionTypeDescriptionExample
dl-programnullaryCreate Datalog program(dl-program)
dl-add-edbvariadicRegister base relation (table + arity)(dl-add-edb prog 'edge tbl 2)
dl-stratifyunaryCompute strata for the program(dl-stratify prog)
dl-evalunaryEvaluate program to fixpoint(dl-eval prog)
dl-querybinaryQuery a derived or base relation(dl-query prog 'edge)
dl-provenancebinaryGet derivation tracking (if available)(dl-provenance prog 'rel)
; Low-level Datalog program
(set prog (dl-program))
(set edges (table [x y] (list [1 2 3] [2 3 4])))
(dl-add-edb prog 'edge edges 2)
(dl-stratify prog)
(dl-eval prog)
(dl-query prog 'edge)  ; returns the edge table