Skip to content

Standard Library

Sema ships with a comprehensive standard library of built-in functions across many modules, covering everything from string manipulation and file I/O to HTTP requests, regex, and cryptographic hashing.

Naming Conventions

Sema's stdlib follows consistent naming patterns:

PatternConventionExample
module/functionSlash-namespacedstring/trim, file/read, math/gcd
legacy-nameScheme compat aliasesstring-appendstring/append
type->typeArrow conversionsstring/to-symbol, list->vector
predicate?Predicate suffixnull?, list?, even?

Naming aliases

Several functions are registered under both a legacy (Scheme-style) name and a canonical slash-namespaced or predicate? name (Decision #24). Both forms are kept for backward compatibility; new code should prefer the canonical form on the right.

Legacy nameCanonical alias
anyany?
everyevery?
time-mstime/now-ms
hash-mapmap/new
promise-forced?async/forced?
tools->routesroute/from-tools
make-bytevectorbytevector/make (also bytevector/new)
bytevector-lengthbytevector/length
bytevector-u8-refbytevector/u8-ref (also bytevector/ref)
bytevector-u8-set!bytevector/u8-set! (also bytevector/set!)
bytevector-copybytevector/copy
bytevector-appendbytevector/append
bytevector->listbytevector/to-list
list->bytevectorbytevector/from-list (also list/to-bytevector)

Predicates (bytevector? etc.) and the bare bytevector varargs constructor keep their short canonical names — predicates always stay un-namespaced.

Quick Reference

Math & Arithmetic

FunctionDescription
+, -, *, /, modBasic arithmetic
<, >, <=, >=, =Comparison
abs, min, max, pow, sqrt, logNumeric utilities
floor, ceil, round, truncateRounding
sin, cos, math/tanTrigonometry
math/asin, math/acos, math/atan, math/atan2Inverse trig
math/sinh, math/cosh, math/tanhHyperbolic
math/exp, math/log10, math/log2Exponential & logarithmic
math/gcd, math/lcm, math/quotient, math/remainderInteger math
math/random, math/random-intRandom numbers
math/clamp, math/sign, math/lerp, math/map-rangeInterpolation & clamping
math/degrees->radians, math/radians->degreesAngle conversion
even?, odd?, positive?, negative?, zero?Numeric predicates
math/nan?, math/infinite?Float predicates
pi, e, math/infinity, math/nanConstants
bit/and, bit/or, bit/xor, bit/not, bit/shift-left, bit/shift-rightBitwise operations

Strings & Characters

FunctionDescription
string/append, string/length, string/ref, string/sliceCore string ops
str, formatConversion & formatting
string/split, string/join, string/trimSplit, join, trim
string/upper, string/lower, string/capitalize, string/title-caseCase conversion
string/contains?, string/starts-with?, string/ends-with?Search predicates
string/replace, string/index-of, string/last-index-of, string/reverseManipulation
string/chars, string/repeat, string/pad-left, string/pad-rightUtilities
string/map, string/number?, string/empty?Higher-order & predicates
string/after, string/before, string/between, string/takeSlicing & extraction
string/chop-start, string/chop-end, string/ensure-start, string/ensure-endPrefix & suffix
string/wrap, string/unwrap, string/removeWrapping & removal
string/replace-first, string/replace-lastTargeted replacement
string/snake-case, string/kebab-case, string/camel-case, string/pascal-caseCase conversion
string/headline, string/wordsHeadline & word splitting
char/to-integer, integer/to-char, char/alphabetic?, ...Character operations
string/to-number, number/to-string, string/to-symbol, ...Type conversions

Lists

FunctionDescription
list, cons, car, cdr, first, restConstruction & access
cadr, caddr, last, nthPositional access
length, append, reverse, rangeBasic operations
map, filter, foldl, foldr, reduce, flat-mapHigher-order functions
sort, sort-by, apply, for-eachOrdering & application
take, drop, flatten, flatten-deep, zip, partitionSublists
member, any, every, list/index-of, list/unique, list/dedupeSearching
list/group-by, list/interleave, list/chunk, frequenciesGrouping
list/sum, list/min, list/maxAggregation
list/shuffle, list/pickRandom
list/repeat, make-list, iotaConstruction
list/split-at, list/take-while, list/drop-whileSplitting
assoc, assq, assvAssociation lists
interposeInterleaving
list/reject, list/find, list/soleFiltering & searching
list/pluck, list/key-byMap extraction
list/avg, list/median, list/modeStatistics
list/diff, list/intersect, list/duplicatesSet operations
list/sliding, list/page, list/cross-joinWindowing & pagination
list/pad, list/join, list/timesPadding, joining & generation
tapUtility

Vectors

FunctionDescription
vectorCreate a vector
vector->list, list->vectorConversion

Maps & HashMaps

FunctionDescription
map/new, get, assoc, dissoc, mergeCore map ops
keys, vals, contains?, countInspection
map/entries, map/from-entriesEntry conversion
map/map-vals, map/map-keys, map/filterHigher-order
map/select-keys, map/updateSelection & update
map/sort-keys, map/except, map/zipSorting, exclusion & zipping
hashmap/new, hashmap/get, hashmap/assoc, ...HashMap operations

Predicates & Type Checking

FunctionDescription
null?, nil?, empty?, list?, pair?Collection predicates
number?, integer?, float?, string?, symbol?, keyword?Type predicates
char?, record?, bytevector?, bool?, fn?More type predicates
map?, vector?Container predicates
promise?, promise-forced?Promise predicates
eq?, =, zero?, even?, odd?, positive?, negative?Equality & numeric
prompt?, message?, conversation?, tool?, agent?LLM type predicates

File I/O & Paths

FunctionDescription
display, println, pprint, print, io/print-error, io/println-error, newline, io/read-line, io/read-stdin, io/eof?, io/flushConsole I/O
file/read, file/write, file/appendFile read/write
file/read-bytes, file/write-bytesBinary file I/O
file/read-lines, file/write-linesLine-based I/O
file/for-each-line, file/fold-linesStreaming line I/O
file/delete, file/rename, file/copyFile management
file/exists?, file/is-file?, file/is-directory?, file/is-symlink?File predicates
file/list, file/mkdir, file/infoDirectory operations
file/globFile globbing
path/join, path/dirname, path/basename, path/extension, path/absolutePath manipulation
path/ext, path/stem, path/dir, path/filename, path/absolute?Path predicates & components

PDF Processing

FunctionDescription
pdf/extract-textExtract all text from a PDF
pdf/extract-text-pagesExtract text per page (returns list)
pdf/page-countGet number of pages
pdf/metadataGet metadata map (:title, :author, :pages, ...)

HTTP & JSON

FunctionDescription
http/get, http/post, http/put, http/delete, http/requestHTTP methods
json/encode, json/encode-pretty, json/decodeJSON serialization

Web Server

FunctionDescription
http/serveStart an HTTP server
http/routerData-driven routing
http/ok, http/created, http/no-content, http/not-found, http/errorJSON response helpers
http/redirectHTTP redirect
http/html, http/textContent-type responses
http/fileServe a file from disk
http/streamSSE streaming
http/websocketWebSocket connections

Regex

FunctionDescription
regex/match?, regex/match, regex/find-allMatching
regex/replace, regex/replace-all, regex/splitReplacement & splitting

CSV, Crypto & Encoding

FunctionDescription
csv/parse, csv/parse-maps, csv/encodeCSV operations
uuid/v4UUID generation
base64/encode, base64/decodeBase64 encoding
base64/encode-bytes, base64/decode-bytesBinary Base64
hash/sha256, hash/md5, hash/hmac-sha256Hashing

Date & Time

FunctionDescription
time/now, time-msCurrent time
time/format, time/parseFormatting & parsing
time/date-partsDate decomposition
time/add, time/diffArithmetic
sleepDelay execution

System

FunctionDescription
env, sys/env-all, sys/set-envEnvironment variables
sys/args, sys/cwd, sys/platform, sys/os, sys/archSystem info
sys/pid, sys/tty, sys/which, sys/elapsedProcess info
sys/interactive?, sys/hostname, sys/userSession info
sys/home-dir, sys/temp-dirDirectory paths
sys/term-sizeTerminal size (Unix)
sys/on-signal, sys/check-signalsSignal hooks (Unix)
shellRun shell commands
exitExit process

Serial Ports

FunctionDescription
serial/listList available device paths
serial/open, serial/closeOpen/close a port (returns int handle)
serial/write, serial/read-lineRaw I/O
serial/sendWrite line + read JSON response

Bytevectors

FunctionDescription
bytevector, bytevector/newConstruction
bytevector/length, bytevector/ref, bytevector/set!Access & mutation
bytevector/copy, bytevector/appendCopy & append
bytevector/to-list, list/to-bytevectorList conversion
utf8/to-string, string/to-utf8String conversion

Streams

FunctionDescription
stream/from-string, stream/from-bytes, stream/byte-bufferIn-memory streams
stream/open-input, stream/open-outputFile streams
stream/read, stream/read-byte, stream/read-line, stream/read-allReading
stream/write, stream/write-byte, stream/write-stringWriting
stream/close, stream/flush, stream/copyControl
stream?, stream/readable?, stream/writable?, stream/available?Predicates
stream/type, stream/to-bytes, stream/to-stringIntrospection & extraction
*stdin*, *stdout*, *stderr*Standard I/O globals
with-streamResource management macro

Concurrency

FunctionDescription
async/spawn, async/await, async/all, async/raceAsync task management
async/resolved, async/rejectedPre-settled promises
async/run, async/sleep, async/timeoutScheduler control & deadlines
async/cancel, async/cancelled?Cancellation
async/promise?, async/resolved?, async/rejected?, async/pending?Promise predicates
channel/new, channel/send, channel/recv, channel/try-recvChannel operations
channel/closeChannel lifecycle
channel?, channel/closed?, channel/empty?, channel/full?, channel/countChannel predicates

Records

FunctionDescription
define-record-typeDefine a record type
record?Record predicate
typeGet record type tag

Terminal Styling

FunctionDescription
term/bold, term/red, term/green, ...Individual style functions
term/styleApply multiple styles with keywords
term/rgb24-bit true color
term/stripRemove ANSI escape codes
term/spinner-start, term/spinner-stop, term/spinner-updateAnimated spinners
io/tty-raw!, io/tty-restore!Raw-mode TTY (Unix)
io/read-key, io/read-key-timeoutPer-keystroke input (Unix)

Text Processing

FunctionDescription
text/chunk, text/chunk-by-separator, text/split-sentencesText chunking
text/clean-whitespace, text/strip-htmlText cleaning
text/truncate, text/word-count, text/trim-indentText utilities
text/excerpt, text/normalize-newlinesExcerpt extraction & newline normalization
prompt/template, prompt/renderPrompt templates
document/create, document/text, document/metadata, document/chunkDocument metadata

SQLite

FunctionDescription
db/open, db/open-memoryOpen file or in-memory database
db/exec, db/exec-batchExecute statements
db/query, db/query-oneQuery rows as maps
db/last-insert-idLast inserted rowid
db/tablesList tables
db/closeClose connection

Typed Arrays

FunctionDescription
f64-array, i64-arrayCreate from values
f64-array/make, i64-array/makeCreate with fill
f64-array/range, i64-array/rangeCreate from range
f64-array/from-list, i64-array/from-listConvert from list
f64-array/ref, i64-array/refIndex access
f64-array/set!, i64-array/set!Set element (CoW)
f64-array/length, i64-array/lengthLength
f64-array/sum, i64-array/sumFast sum
f64-array/dotDot product
f64-array/map, i64-array/mapMap over elements
f64-array/fold, i64-array/foldFold over elements
f64-array?, i64-array?Type predicates

Context

FunctionDescription
context/set, context/get, context/has?Core key-value context
context/remove, context/pull, context/allRetrieval & cleanup
context/merge, context/clearBulk operations
context/withScoped overrides (auto-restores on exit)
context/push, context/stack, context/popNamed stacks
context/set-hidden, context/get-hidden, context/has-hidden?Hidden (non-logged) context

Key-Value Store

FunctionDescription
kv/open, kv/closeOpen/close a JSON-backed store
kv/get, kv/set, kv/deleteCRUD operations
kv/keysList all keys

TOML

FunctionDescription
toml/decodeDecode TOML to Sema
toml/encodeEncode Sema to TOML

Playground & WASM

FunctionDescription
web/user-agentBrowser user agent string (WASM only)
web/user-agent-dataStructured browser info map (Chromium only, WASM only)