Skip to content

Arc Standard Library Reference

Complete API reference for all Arc standard library modules.

All 27 stdlib modules are implemented and tested. The 8 modules requiring native runtime access (regex, datetime, os, io, http, crypto, error, net) all have full native implementations backed by real system calls. 4 AI-native modules (prompt, embed, llm, store) provide first-class support for agent workflows. 6 utility modules (yaml, toml, html, path, env, log) round out the standard library.


Table of Contents


math

Mathematical constants and functions.

arc
use math

Constants

ConstantValueDescription
PI3.141592653589793Ratio of circle's circumference to diameter
E2.718281828459045Euler's number
TAU6.2831853071795862π — full circle in radians

Functions

FunctionSignatureDescription
abs(x) -> NumberAbsolute value
sign(x) -> NumberSign of number (-1, 0, or 1)
clamp(x, lo, hi) -> NumberConstrain to range [lo, hi]
ceil(x) -> IntSmallest integer ≥ x
floor(x) -> IntLargest integer ≤ x
round(x) -> IntRound to nearest integer
pow(base, exp) -> NumberRaise base to power
sqrt(x) -> Number | nilSquare root (nil for negative)
cbrt(x) -> NumberCube root
hypot(a, b) -> NumberHypotenuse (√(a²+b²))
sin(x) -> NumberSine (radians)
cos(x) -> NumberCosine (radians)
tan(x) -> NumberTangent (radians)
asin(x) -> NumberArcsine
acos(x) -> NumberArccosine
atan(x) -> NumberArctangent
atan2(y, x) -> NumberTwo-argument arctangent
degrees(radians) -> NumberConvert radians to degrees
radians(degrees) -> NumberConvert degrees to radians
log(x) -> NumberNatural logarithm
log2(x) -> NumberBase-2 logarithm
log10(x) -> NumberBase-10 logarithm
exp(x) -> Numbere^x
factorial(n) -> IntFactorial
gcd(a, b) -> IntGreatest common divisor
lcm(a, b) -> IntLeast common multiple
sum(list) -> NumberSum of a list
product(list) -> NumberProduct of a list
arc
math.abs(-5)       # => 5
math.pow(2, 10)    # => 1024
math.sqrt(144)     # => 12
math.round(4.6)    # => 5
math.sin(math.PI)  # => ~0
math.sum([1,2,3])  # => 6

strings

String manipulation utilities beyond the built-in string functions.

arc
use strings

Functions

pad_left(s, width, ch) -> String

Pads string s on the left with character ch until it reaches width.

arc
strings.pad_left("42", 5, "0")    # => "00042"
strings.pad_left("hello", 3, " ") # => "hello"  (already >= width)

pad_right(s, width, ch) -> String

Pads string s on the right with character ch until it reaches width.

arc
strings.pad_right("hi", 5, ".")   # => "hi..."

capitalize(s) -> String

Capitalizes the first letter and lowercases the rest.

arc
strings.capitalize("hello")   # => "Hello"
strings.capitalize("aRC")     # => "Arc"
strings.capitalize("")        # => ""

words(s) -> [String]

Splits a string into a list of words (split by spaces, trimmed, empty strings removed).

arc
strings.words("  hello   world  ")  # => ["hello", "world"]

collections

List, set, and queue utilities.

arc
use collections

Functions

FunctionSignatureDescription
set(list) -> [Any]Remove duplicates (returns deduplicated list)
unique(list) -> [Any]Alias for set
group_by(list, fn) -> MapGroup elements by key function
count_by(list, fn) -> MapCount elements by key function
chunk(list, size) -> [[Any]]Split list into chunks
flatten(nested) -> [Any]Flatten nested lists one level
zip_with(a, b, fn) -> [Any]Combine two lists element-wise with a function
partition(list, fn) -> [[Any], [Any]]Split list into [matches, non-matches]
frequencies(list) -> MapCount occurrences of each element
min_by(list, fn) -> AnyMinimum element by key function
max_by(list, fn) -> AnyMaximum element by key function
sort_by(list, fn) -> [Any]Sort by key function
index_of(list, val) -> Int | nilIndex of first occurrence
includes(list, val) -> BoolCheck if list contains value

Built-in list functions (map, filter, reduce, take, skip, find, contains, len, push, concat) are available without use.


map

Map/dictionary utilities.

arc
use map

Functions

FunctionSignatureDescription
merge(a, b) -> MapMerge two maps (b overwrites a)
map_values(m, fn) -> MapTransform all values
map_keys(m, fn) -> MapTransform all keys
filter_map(m, fn) -> MapFilter entries by predicate
from_pairs(pairs) -> MapCreate map from key-value pairs
to_pairs(m) -> [(Any, Any)]Convert map to key-value pairs
pick(m, keys) -> MapSelect only specified keys
omit(m, keys) -> MapRemove specified keys

Built-in keys(m), values(m) are available without use.


io

File and console I/O with native Node.js fs implementation.

arc
use io

Functions

FunctionSignatureDescription
read_file(path) -> Result<String>Read file contents
write_file(path, content) -> Result<nil>Write string to file
read_lines(path) -> Result<[String]>Read file as lines
write_lines(path, lines) -> Result<nil>Write list of lines to file
exists(path) -> BoolCheck if path exists
append(path, content) -> Result<nil>Append string to file

print(...) is a built-in and does not require import.


http

HTTP client with native fetch implementation via sync bridge.

arc
use http

Functions

FunctionSignatureDescription
get(url, headers?) -> Result<Response>HTTP GET
post(url, body, headers?) -> Result<Response>HTTP POST
put(url, body, headers?) -> Result<Response>HTTP PUT
delete(url, headers?) -> Result<Response>HTTP DELETE
fetch_all(requests) -> [Result<Response>]Execute multiple HTTP requests
parse_url(url) -> MapParse URL into components

Arc also supports the @GET, @POST syntax for inline HTTP calls — see the Language Tour.


json

JSON serialization and deserialization.

arc
use json

Functions

FunctionSignatureDescription
from_json(s: String) -> Result<Any>Parse JSON string to Arc value
to_json(value, indent?) -> StringConvert Arc value to JSON string
pretty(value) -> StringPretty-print with 2-space indent
get_path(value, path) -> AnyGet nested value by dot-separated path

csv

CSV parsing and generation.

arc
use csv

Functions

FunctionSignatureDescription
parse_csv(s: String, sep?) -> [[String]]Parse CSV to rows
parse_csv_headers(s: String, sep?) -> [Map]Parse CSV with header row to maps
to_csv(rows: [[String]], sep?) -> StringConvert rows to CSV string

test

Testing framework.

arc
use test

Functions

FunctionSignatureDescription
describe(name, fn)Define a test suite
it(name, fn)Define a test case
expect_eq(a, b)Assert equality
expect_neq(a, b)Assert inequality
expect_true(cond)Assert truthy
expect_false(cond)Assert falsy
expect_nil(val)Assert nil
expect_gt(a, b)Assert a > b
expect_lt(a, b)Assert a < b
run_tests()Run all defined test suites

Example

arc
use test

test.describe("math", fn() {
  test.it("adds numbers", fn() {
    test.expect_eq(1 + 1, 2)
  })
  test.it("strings are non-empty", fn() {
    test.expect_true(len("hello") > 0)
  })
})

test.run_tests()

result

Error handling with Result types.

arc
use result

Arc uses Result<T> as the standard error-handling pattern — either Ok(value) or Err(message).

Functions

FunctionSignatureDescription
ok(value) -> Result<T>Wrap value in Ok
err(msg) -> Result<T>Create an Err
is_ok(r) -> BoolCheck if Ok
is_err(r) -> BoolCheck if Err
unwrap(r) -> TGet value or panic
unwrap_or(r, default) -> TGet value or default
unwrap_err(r) -> StringGet error message or panic
map(r, fn) -> Result<U>Transform Ok value
flat_map(r, fn) -> Result<U>Chain Result-returning functions
try_fn(fn) -> Result<T>Run function, catching errors as Err
result_is_ok(r) -> BoolCheck if Ok (alternate form)
result_is_err(r) -> BoolCheck if Err (alternate form)
result_unwrap(r) -> TUnwrap (alternate form)
result_unwrap_or(r, default) -> TUnwrap or default (alternate form)
result_map(r, fn) -> Result<U>Map Ok value (alternate form)
flat_map_result(r, fn) -> Result<U>Chain Results (alternate form)

Example

arc
use result

let r = result.ok(42)
let doubled = r |> result.map(x => x * 2)  # Ok(84)

let e = result.err("not found")
result.unwrap_or(e, 0)  # => 0

time

Date, time, and duration utilities.

arc
use time

Functions

FunctionSignatureDescription
now() -> TimestampCurrent Unix timestamp (ms)
format_duration(ms) -> StringFormat milliseconds as human-readable duration
sleep(ms)Pause execution

Built-in Functions (No use Required)

These are available globally in every Arc program:

FunctionDescription
print(...)Print to stdout
len(x)Length of string, list, or map
str(x)Convert to string
int(x)Convert to integer
float(x)Convert to float
type(x)Get type name as string
split(s, sep)Split string by separator
join(list, sep)Join list into string
trim(s)Trim whitespace
upper(s)Uppercase string
lower(s)Lowercase string
slice(x, start, end)Slice string or list
map(list, fn)Transform each element
filter(list, fn)Keep matching elements
reduce(list, fn, init)Fold list to single value
find(list, fn)Find first match
contains(list, val)Check membership
push(list, val)Append to list
concat(a, b)Concatenate lists
take(list, n)First n elements
skip(list, n)Skip first n elements
sort(list)Sort list
reverse(list)Reverse list
keys(map)Map keys
values(map)Map values

regex

Regular expression operations with native implementation and ReDoS protection.

arc
use regex

Functions

FunctionSignatureDescription
find(pattern, str) -> Match | nilFind first match
find_all(pattern, str) -> [Match]Find all matches
match_all(pattern, str) -> [Match]All matches (alias for find_all)
test(pattern, str) -> BoolTest if pattern matches
replace(pattern, str, replacement) -> StringReplace first match
replace_first(pattern, str, replacement) -> StringReplace first match
replace_all(pattern, str, replacement) -> StringReplace all matches
split(pattern, str) -> [String]Split by pattern
capture(pattern, str) -> [String] | nilCapture groups from first match
capture_all(pattern, str) -> [[String]]All capture groups
escape(str) -> StringEscape regex metacharacters
is_valid(pattern) -> BoolCheck if pattern is valid regex

datetime

Date and time operations with native implementation.

arc
use datetime

Functions

FunctionSignatureDescription
now() -> NumberCurrent Unix timestamp (milliseconds)
today() -> MapCurrent date as {year, month, day, hour, minute, second, ms}
parse(str) -> TimestampParse date string
format(ts, fmt) -> StringFormat timestamp
add_days(ts, days) -> TimestampAdd days to timestamp
add_hours(ts, hours) -> TimestampAdd hours to timestamp
add_minutes(ts, minutes) -> TimestampAdd minutes to timestamp
diff_days(a, b) -> NumberDays between two timestamps
diff_hours(a, b) -> NumberHours between two timestamps
diff_minutes(a, b) -> NumberMinutes between two timestamps
day_of_week(ts) -> StringDay of week name
is_before(a, b) -> BoolCheck if timestamp a is before b
is_after(a, b) -> BoolCheck if timestamp a is after b
to_iso(ts) -> StringConvert timestamp to ISO 8601 string
from_iso(str) -> TimestampParse ISO 8601 string to timestamp

os

Operating system interaction with native implementation. Includes command injection protection.

arc
use os

Functions

FunctionSignatureDescription
cwd() -> StringCurrent working directory
get_env(name) -> String | nilGet environment variable
env(name) -> String | nilGet environment variable (alias)
set_env(name, value) -> nilSet environment variable
list_dir(path) -> [String]List directory contents
is_file(path) -> BoolCheck if path is a file
is_dir(path) -> BoolCheck if path is a directory
mkdir(path) -> nilCreate directory
rmdir(path) -> nilRemove directory
remove(path) -> nilRemove file
rename(from, to) -> nilRename/move file
copy(src, dst) -> nilCopy file
file_size(path) -> IntGet file size in bytes
file_ext(path) -> StringGet file extension
join_path(...parts) -> StringJoin path segments
parent_dir(path) -> StringGet parent directory
basename(path) -> StringGet file name from path
exec(cmd) -> MapExecute shell command (10s timeout, injection-protected)
platform() -> StringOS platform name
home_dir() -> StringUser home directory
temp_dir() -> StringTemp directory path

error

Error handling utilities with native implementation.

arc
use error

Functions

FunctionSignatureDescription
error(msg) -> ErrorCreate an error value
is_error(val) -> BoolCheck if value is an error
wrap_error(msg, cause) -> ErrorWrap an error with additional context
try_fn(fn) -> ResultRun function, catching errors as Result
try_catch(fn, handler) -> AnyTry/catch wrapper
try_finally(fn, cleanup) -> AnyTry/finally wrapper
try_catch_finally(fn, handler, cleanup) -> AnyTry/catch/finally wrapper
throw(msg) -> neverThrow an error
retry(fn, attempts) -> ResultRetry a function on failure

net

Networking utilities with native implementation.

arc
use net

Functions

FunctionSignatureDescription
url_parse(url) -> MapParse URL into components
url_encode(str) -> StringURL encode
url_decode(str) -> StringURL decode
parse_query(str) -> MapParse query string
build_query(map) -> StringBuild query string from map
ip_is_valid(str) -> BoolValidate IP address

crypto

Cryptographic operations with native implementation.

arc
use crypto

Functions

FunctionSignatureDescription
md5(str) -> StringMD5 hash
sha1(str) -> StringSHA-1 hash
sha256(str) -> StringSHA-256 hash
sha512(str) -> StringSHA-512 hash
hmac_sha256(key, data) -> StringHMAC-SHA256
hmac_sha512(key, data) -> StringHMAC-SHA512
random_bytes(n) -> StringRandom bytes (hex)
random_int(min, max) -> IntRandom integer in range
uuid() -> StringGenerate UUID v4
base64_encode(str) -> StringBase64 encode
base64_decode(str) -> StringBase64 decode
hash_password(password) -> StringHash a password
verify_password(password, hash) -> BoolVerify password against hash
constant_time_eq(a, b) -> BoolConstant-time string comparison

prompt

Template management, token counting, and context windowing for AI agents.

arc
use prompt

Functions

FunctionSignatureDescription
template(tmpl, vars) -> StringFill <<var>> placeholders from a map
token_count(text) -> IntEstimate token count (~4 chars/token)
token_truncate(text, max_tokens) -> StringTruncate text to fit token limit
context_window(messages, max_tokens) -> [Message]Fit messages within token budget (keeps newest)
chunk(text, max_tokens) -> [String]Split text into token-sized chunks
system_prompt(role, instructions) -> MessageFormat a system message
user_message(text) -> MessageFormat a user message
assistant_message(text) -> MessageFormat an assistant message
format_chat(messages) -> StringFormat message list into chat string

Example

arc
use prompt

let tmpl = "Hello <<name>>, you have <<count>> messages."
let filled = prompt.template(tmpl, {name: "Alice", count: "3"})
# => "Hello Alice, you have 3 messages."

let tokens = prompt.token_count(filled)
# => ~11

embed

Vector embeddings, similarity search, and distance calculations.

arc
use embed

Functions

FunctionSignatureDescription
dot_product(vec_a, vec_b) -> NumberDot product of two vectors
magnitude(vec) -> NumberVector magnitude (L2 norm)
cosine_similarity(vec_a, vec_b) -> NumberCosine similarity (-1 to 1)
normalize(vec) -> [Number]Normalize to unit vector
euclidean_distance(vec_a, vec_b) -> NumberEuclidean distance
centroid(vectors) -> [Number]Average vector (centroid)
most_similar(query_vec, candidates, top_k) -> [{id, score}]Top-k most similar vectors
chunk_and_embed(text, chunk_size) -> [{chunk, index}]Split text into chunks

Example

arc
use embed

let a = [1.0, 0.0, 0.0]
let b = [0.0, 1.0, 0.0]
embed.cosine_similarity(a, b)  # => 0.0 (orthogonal)

let candidates = [
  {id: "doc1", vector: [0.9, 0.1, 0.0]},
  {id: "doc2", vector: [0.0, 0.8, 0.2]}
]
embed.most_similar(a, candidates, 1)  # => [{id: "doc1", score: ~0.99}]

llm

Multi-provider LLM API integration for AI agent workflows.

arc
use llm

Functions

FunctionSignatureDescription
chat(provider, model, messages, options?) -> ResultSend chat completion request
complete(provider, model, prompt, options?) -> ResultSimple text completion
stream(provider, model, messages, callback) -> ResultStreaming chat (calls callback with response)
models(provider) -> [String]List available models
estimate_cost(model, input_tokens, output_tokens) -> CostEstimate API cost in USD
providers() -> [Provider]List supported providers

Supported providers: "openai", "anthropic"

Example

arc
use llm

let result = llm.chat("openai", "gpt-4o", [
  {role: "system", content: "You are a helpful assistant."},
  {role: "user", content: "What is Arc?"}
], {temperature: 0.7})

if result.ok {
  print(result.content)
}

# Estimate costs
let cost = llm.estimate_cost("gpt-4o", 1000, 500)
print("Cost: ${cost.total}")

store

Persistent JSON-backed key-value storage.

arc
use store

Functions

FunctionSignatureDescription
open(path) -> StoreOpen or create a JSON store file
get(store, key) -> Any | nilGet value by key
set(store, key, value) -> nilSet key-value pair
delete(store, key) -> nilDelete a key
has(store, key) -> BoolCheck if key exists
keys(store) -> [String]Get all keys
values(store) -> [Any]Get all values
entries(store) -> [(String, Any)]Get all key-value pairs
clear(store) -> nilRemove all entries
size(store) -> IntNumber of entries
merge(store, map) -> nilMerge a map into the store
get_or_set(store, key, default_fn) -> AnyGet existing or set default

Example

arc
use store

let db = store.open("settings.json")
store.set(db, "theme", "dark")
store.set(db, "lang", "en")

let theme = store.get(db, "theme")  # => "dark"
store.has(db, "lang")               # => true
store.keys(db)                      # => ["theme", "lang"]

yaml

YAML parsing and stringifying.

arc
use yaml

Functions

FunctionSignatureDescription
parse(text: String) -> AnyParse YAML string to Arc value
stringify(value) -> StringConvert Arc value to YAML string

Example

arc
use yaml

let data = yaml.parse("name: Alice\nage: 30")
# => {name: "Alice", age: 30}

let text = yaml.stringify({host: "localhost", port: 8080})
# => "host: localhost\nport: 8080\n"

toml

TOML parsing and stringifying.

arc
use toml

Functions

FunctionSignatureDescription
parse(text: String) -> AnyParse TOML string to Arc value
stringify(value) -> StringConvert Arc value to TOML string

Example

arc
use toml

let config = toml.parse("[server]\nhost = \"localhost\"\nport = 8080")
# => {server: {host: "localhost", port: 8080}}

let text = toml.stringify({title: "My App", version: "1.0"})

html

HTML parsing and generation utilities.

arc
use html

Functions

FunctionSignatureDescription
parse(s: String) -> NodeParse HTML string into a node tree
select(node, selector: String) -> [Node]Query nodes by CSS selector
text(node) -> StringExtract text content from a node
attr(node, name: String) -> String | nilGet attribute value
create(tag, attrs, children) -> NodeCreate an HTML node
render(node) -> StringRender node tree to HTML string

Example

arc
use html

let doc = html.parse("<div class='main'><p>Hello</p></div>")
let paragraphs = html.select(doc, "p")
let content = html.text(paragraphs[0])  # => "Hello"

let node = html.create("a", {href: "/about"}, ["About Us"])
html.render(node)  # => "<a href=\"/about\">About Us</a>"

path

Path manipulation utilities.

arc
use path

Functions

FunctionSignatureDescription
join(...parts) -> StringJoin path segments
dirname(p: String) -> StringDirectory name
basename(p: String) -> StringFile name
extname(p: String) -> StringFile extension
resolve(p: String) -> StringResolve to absolute path
normalize(p: String) -> StringNormalize path separators and dots
is_absolute(p: String) -> BoolCheck if path is absolute
sep() -> StringPlatform path separator

Example

arc
use path

path.join("src", "lib", "utils.arc")  # => "src/lib/utils.arc"
path.dirname("/home/user/file.arc")    # => "/home/user"
path.basename("/home/user/file.arc")   # => "file.arc"
path.extname("main.arc")              # => ".arc"
path.is_absolute("/usr/bin")          # => true

env

Environment variable utilities.

arc
use env

Functions

FunctionSignatureDescription
get(key: String) -> String | nilGet environment variable
get_or(key: String, default: String) -> StringGet with default fallback
set(key: String, val: String) -> nilSet environment variable
remove(key: String) -> nilRemove environment variable
has(key: String) -> BoolCheck if variable exists
list() -> MapGet all environment variables
require(key: String) -> StringGet or panic if missing

Example

arc
use env

env.set("APP_ENV", "production")
let mode = env.get_or("APP_ENV", "development")  # => "production"
env.has("APP_ENV")                                 # => true

let db_url = env.require("DATABASE_URL")  # panics if not set

log

Structured logging with levels and colors.

arc
use log

Functions

FunctionSignatureDescription
debug(msg: String) -> nilLog at debug level
info(msg: String) -> nilLog at info level
warn(msg: String) -> nilLog at warn level
error(msg: String) -> nilLog at error level
fatal(msg: String) -> neverLog and exit
set_level(level: String) -> nilSet minimum log level
with(fields: Map) -> LoggerCreate child logger with extra fields
json(level, msg, fields) -> nilEmit structured JSON log entry
child_debug(logger, msg) -> nilLog debug with child logger
child_info(logger, msg) -> nilLog info with child logger
child_warn(logger, msg) -> nilLog warn with child logger
child_error(logger, msg) -> nilLog error with child logger

Example

arc
use log

log.set_level("info")
log.info("Server started")
log.warn("Disk usage high")
log.error("Connection failed")

let logger = log.with({service: "api", version: "1.0"})
log.child_info(logger, "Request received")  # Log with child logger context

log.json("info", "request", {method: "GET", path: "/api/users", status: 200})

A programming language designed by AI agents, for AI agents.