Standard Library Reference¶
This page documents all built-in functions available in Endo. Functions are grouped by category. Each example is executable and verified by the documentation test suite.
Contents¶
- 15.1 Output --
print,println - 15.2 Type Conversion --
string_length,int_of_string,string_of_int,string,not - 15.3 String Operations --
trim,toLower,toUpper,contains,startsWith,endsWith,replace,split,join,* - 15.4 List -- Basic Operations --
head,tail,length,isEmpty,nth,last,replicate - 15.5 List -- Higher-Order Functions --
map,filter,fold,reduce,find,exists,forall,each - 15.6 List -- Transformations --
sort,reverse,distinct,sortBy,groupBy,take,drop,zip,flatten - 15.7 List -- Operators --
::,@ - 15.8 Option Combinators --
Option.map,Option.bind,Option.defaultValue - 15.9 Environment & System --
env,which - 15.10 Random --
rand - 15.11 Number Formatting --
formatNumber - 15.12 Composition Examples
- 15.13 Size Type --
Size.fromBytes,Size.fromKB,Size.fromMB,Size.fromGB,Size.fromTB, size literals - 15.14 DateTime Type --
DateTime.now,DateTime.fromEpoch,formatDateTime - 15.15 TimeSpan Type --
TimeSpan.fromMilliseconds,TimeSpan.fromSeconds,TimeSpan.fromMinutes,TimeSpan.fromHours,TimeSpan.fromDays,sleep,formatTimeSpan - 15.16 Shell Data Commands --
ls,ps,jobs - 15.17 FileMode Type --
FileMode.fromBits,.isReadable,.isWritable,.isExecutable,.owner,.group,.other - 15.18 File Permission Helpers --
formatMode,isReadable,isWritable,isExecutable - 15.19 Display Formatting --
toText,string - 15.20 HTTP --
fetch - 15.21 Timing --
time - 15.22 JSON --
Json.query - 15.23 Lazy Evaluation --
force - 15.24 Lazy Sequences --
seq,yield,yield!,toList - 15.25 Path --
Path.temporary_directory - 15.26 File I/O --
File.open,File.close,File.readLine,File.readAll,File.writeAll,File.appendAll,File.size,File.exists,File.delete - 15.27 Resource Management --
let use,let manual
15.1 Output¶
print¶
Signature: print value
Prints a value to stdout without a trailing newline.
println¶
Signature: println value
Prints a value to stdout followed by a newline.
15.2 Type Conversion¶
string_length¶
Signature: string_length str : int
Returns the number of characters in a string.
int_of_string¶
Signature: int_of_string str : int
Converts a string to an integer.
string_of_int¶
Signature: string_of_int n : str
Converts an integer to its string representation.
string¶
Signature: string value : str
Universal conversion to string. Works with integers, floats, booleans, and strings (passthrough).
println (string 42) # => 42
println (string 3.14) # => 3.14
println (string true) # => true
println (string "hi") # => hi
not¶
Signature: not value : bool
Boolean negation.
15.3 String Operations¶
trim¶
Signature: trim str : str
Removes leading and trailing whitespace.
toLower¶
Signature: toLower str : str
Converts a string to lowercase.
toUpper¶
Signature: toUpper str : str
Converts a string to uppercase.
contains¶
Signature: contains substr text : bool
Returns true if text contains the substring substr.
startsWith¶
Signature: startsWith prefix text : bool
Returns true if text starts with the given prefix.
endsWith¶
Signature: endsWith suffix text : bool
Returns true if text ends with the given suffix.
replace¶
Signature: replace old new str : str
Replaces all occurrences of old with new in the string.
split¶
Signature: split separator str : list<str>
Splits a string by the given separator, returning a list of substrings.
join¶
Signature: join separator list : str
Joins a list of strings with the given separator.
String Repetition (*)¶
Repeats a string a given number of times.
15.4 List -- Basic Operations¶
head¶
Signature: head list : option<T>
Returns the first element wrapped in Some, or None for an empty list.
tail¶
Signature: tail list : list<T>
Returns all elements except the first. Returns [] for an empty list.
length¶
Signature: length list : int
Returns the number of elements in a list.
isEmpty¶
Signature: isEmpty list : bool
Returns true if the list has no elements.
nth¶
Signature: nth index list : option<T>
Returns the element at the given zero-based index, wrapped in Some. Returns None if out of bounds.
last¶
Signature: last list : option<T>
Returns the last element wrapped in Some, or None for an empty list.
replicate¶
Signature: replicate n value : list<T>
Creates a list of n copies of the given value.
15.5 List -- Higher-Order Functions¶
map¶
Signature: map f list : list<U>
Applies f to each element and returns a new list of results.
filter¶
Signature: filter predicate list : list<T>
Returns a list of elements for which the predicate returns true.
fold¶
Signature: fold initial f list : T
Reduces a list to a single value by applying f to the accumulator and each element, starting from initial.
reduce¶
Signature: reduce f list : option<T>
Like fold, but uses the first element as the initial value. Returns Some result or None for empty lists.
find¶
Signature: find predicate list : option<T>
Returns Some element for the first element matching the predicate, or None if no element matches.
exists¶
Signature: exists predicate list : bool
Returns true if any element satisfies the predicate.
forall¶
Signature: forall predicate list : bool
Returns true if all elements satisfy the predicate. Returns true for empty lists.
each¶
Signature: each f list : unit
Applies f to each element for side effects. Returns unit.
15.6 List -- Transformations¶
sort¶
Signature: sort list : list<int>
Sorts a list of integers in ascending order.
reverse¶
Signature: reverse list : list<T>
Returns a new list with elements in reverse order.
distinct¶
Signature: distinct list : list<int>
Removes duplicate elements, preserving first-seen order.
sortBy¶
Signature: sortBy keyFn list : list<T>
Sorts a list by a key function. Uses stable sort (preserves relative order for equal keys).
groupBy¶
Signature: groupBy keyFn list : list<(key, list<T>)>
Groups elements by a key function. Returns a list of (key, elements) tuples.
take¶
Signature: take n list : list<T>
Returns the first n elements. If the list has fewer than n elements, returns the whole list.
drop¶
Signature: drop n list : list<T>
Returns all elements after the first n.
zip¶
Signature: zip listA listB : list<(A, B)>
Combines two lists into a list of tuples. Stops at the shorter list.
flatten¶
Signature: flatten listOfLists : list<T>
Flattens a list of lists into a single list.
15.7 List -- Operators¶
:: (cons)¶
Prepends an element to a list. Right-associative.
@ (concat)¶
Concatenates two lists.
15.8 Option Combinators¶
Option.map¶
Signature: Option.map f option : option<U>
Applies f to the inner value of Some, or returns None unchanged. Can also be used as method-style: opt.map f or in pipelines.
Option.bind¶
Signature: Option.bind f option : option<U>
Applies f (which itself returns an option) to the inner value of Some. Returns None if the input is None or if f returns None. Can also be used as method-style: opt.bind f.
let half (x: int) = if x % 2 == 0 then Some (x / 2) else None
print (Option.bind half (Some 10) ?| 0) # => 5
let half (x: int) = if x % 2 == 0 then Some (x / 2) else None
print (Option.bind half None ?| 0) # => 0
let half (x: int) = if x % 2 == 0 then Some (x / 2) else None
print (Option.bind half (Some 3) ?| 0) # => 0
Option.defaultValue¶
Signature: Option.defaultValue default option : T
Returns the inner value of Some, or the given default for None. Can also be used as method-style: opt.defaultValue def or in pipelines.
15.9 Environment & System¶
env¶
Signature: env name : option<str>
Looks up an environment variable. Returns Some value if the variable is set, None otherwise.
match env "HOME" with
| Some h -> println $"Home: {h}"
| None -> println "HOME not set"
# With the ? operator
let user = (env "USER")?
println user
which¶
Signature: which name : option<str>
Searches $PATH for a program. Returns Some path if found, None otherwise.
match which "git" with
| Some p -> println $"git is at {p}"
| None -> println "git not found"
# With default value
print (which "git" ?| "/default")
15.10 Random¶
rand¶
Signature: rand : int or rand low high : int
With no arguments, returns a random positive integer. With two arguments, returns a random integer in the inclusive range [low, high]. Calling rand with one argument is a compile-time error.
# Random positive integer
let x = rand
println x
# Random integer between 1 and 100
let y = rand 1 100
println y
15.11 Number Formatting¶
formatNumber¶
Signatures: - formatNumber separator number : string — uses the given separator - formatNumber number : string — uses the user's locale thousand separator
Formats an integer with thousand separators for readability. In the 2-argument form, separator is a string inserted every 3 digits from the right. In the 1-argument form, the thousand separator is determined by the user's system locale. Negative numbers are handled correctly (the sign is preserved).
Works in pipelines too:
15.12 Composition Examples¶
These examples combine multiple standard library functions.
15.13 Size Type¶
The Size type represents byte quantities with human-readable display formatting.
Record fields: bytes: int
Size Literals¶
Size values can be written directly using numeric suffixes:
Float values are supported (except for B, which requires whole numbers):
Size.fromBytes¶
Signature: Size.fromBytes n : Size
Creates a Size from a raw byte count.
Size.fromKB¶
Signature: Size.fromKB n : Size
Creates a Size from kilobytes (n × 1024 bytes).
Size.fromMB¶
Signature: Size.fromMB n : Size
Creates a Size from megabytes (n × 1024² bytes).
Size.fromGB¶
Signature: Size.fromGB n : Size
Creates a Size from gigabytes (n × 1024³ bytes).
Size.fromTB¶
Signature: Size.fromTB n : Size
Creates a Size from terabytes (n × 1024⁴ bytes).
Field Access¶
Access the raw byte count via the .bytes field:
Size Comparison¶
Size values support comparison operators:
15.14 DateTime Type¶
The DateTime type represents a point in time (UTC) with named field access.
Record fields: year: int, month: int, day: int, hour: int, minute: int, second: int, epoch: int
DateTime.now¶
Signature: DateTime.now : DateTime
Returns the current UTC date and time.
DateTime.fromEpoch¶
Signature: DateTime.fromEpoch epoch : DateTime
Converts a Unix epoch timestamp to a DateTime record.
let dt = DateTime.fromEpoch 1700000000
println dt.year # 2023
println dt.month # 11
println dt.day # 14
formatDateTime¶
Signature: formatDateTime epoch : str
Formats a Unix epoch timestamp as YYYY-MM-DD HH:MM:SS.
15.15 TimeSpan Type¶
The TimeSpan type represents a duration of time with millisecond precision and human-readable display formatting.
Record fields: milliseconds: int
TimeSpan Literals¶
TimeSpan values can be written directly using numeric suffixes:
Float values are supported (except for ms, which requires whole numbers):
TimeSpan.fromMilliseconds¶
Signature: TimeSpan.fromMilliseconds n : TimeSpan
Creates a TimeSpan from a raw millisecond count.
TimeSpan.fromSeconds¶
Signature: TimeSpan.fromSeconds n : TimeSpan
Creates a TimeSpan from seconds (n × 1000 ms).
TimeSpan.fromMinutes¶
Signature: TimeSpan.fromMinutes n : TimeSpan
Creates a TimeSpan from minutes (n × 60000 ms).
TimeSpan.fromHours¶
Signature: TimeSpan.fromHours n : TimeSpan
Creates a TimeSpan from hours (n × 3600000 ms).
TimeSpan.fromDays¶
Signature: TimeSpan.fromDays n : TimeSpan
Creates a TimeSpan from days (n × 86400000 ms).
Field Access¶
sleep¶
Signature: sleep ts : unit
Pauses execution for the given TimeSpan duration.
formatTimeSpan¶
Signature: formatTimeSpan ts : str
Formats a TimeSpan as a human-readable duration string.
15.16 Shell Data Commands¶
These built-in commands return structured records that support dot access, pattern matching, and pipeline operations.
ls¶
Signature: ls : list<FileInfo> or ls path : list<FileInfo>
Lists directory contents as structured records.
FileInfo fields:
| Field | Type | Description |
|---|---|---|
name | str | File name |
size | Size | File size |
mode | FileMode | Unix file permissions |
mtime | DateTime | Last modification time |
isDir | bool | Whether entry is a directory |
# List all file names
ls |> map _.name
# Find large files (> 1 MB)
ls |> filter (_.size.bytes > 1048576) |> map _.name
# Sort by modification time
ls |> sortBy _.mtime.epoch
# Filter directories only
ls |> filter _.isDir |> map _.name
# Access nested fields
match head ls with
| Some f -> println $"{f.name}: {f.size}"
| None -> println "empty directory"
ps¶
Signature: ps : list<ProcessInfo>
Lists running processes as structured records.
ProcessInfo fields:
| Field | Type | Description |
|---|---|---|
pid | int | Process ID |
ppid | int | Parent process ID |
user | str | Owning user |
cpu | float | CPU usage percentage |
mem | float | Memory usage percentage |
command | str | Command name |
# Filter by CPU usage
ps |> filter (_.cpu > 5.0) |> sortBy _.cpu
# Find processes by name
ps |> filter (_.command |> contains "firefox")
# Count processes per user
ps |> groupBy _.user |> map (fun (u, procs) -> (u, length procs))
jobs¶
Signature: jobs : list<JobInfo>
Lists background jobs as structured records.
JobInfo fields:
| Field | Type | Description |
|---|---|---|
id | int | Job number |
state | str | Job state (e.g. "Running", "Stopped") |
command | str | Command string |
pid | int | Process ID |
15.17 FileMode Type¶
The FileMode type represents Unix file permissions with human-readable display.
| Field | Type | Description |
|---|---|---|
bits | int | Raw permission bits |
Computed properties:
| Property | Type | Description |
|---|---|---|
isReadable | bool | Any read permission bit set |
isWritable | bool | Any write permission bit set |
isExecutable | bool | Any execute permission bit set |
owner | int | Owner digit (0-7) |
group | int | Group digit (0-7) |
other | int | Other digit (0-7) |
FileMode.fromBits¶
Signature: FileMode.fromBits n : FileMode
Creates a FileMode from raw Unix permission bits.
15.18 File Permission Helpers¶
These functions operate on Unix file modes (accept both FileMode objects and raw int permission bits).
formatMode¶
Signature: formatMode mode : str
Formats a Unix file mode as a rwxrwxrwx permission string.
isReadable¶
Signature: isReadable mode : bool
Tests if any read permission bit is set.
isWritable¶
Signature: isWritable mode : bool
Tests if any write permission bit is set.
isExecutable¶
Signature: isExecutable mode : bool
Tests if any execute permission bit is set.
15.19 Display Formatting¶
toText¶
Signature: toText value : str
Converts any value to its string representation. Useful for converting structured records to plain text.
string¶
Signature: string value : str
Universal conversion to string. Works with integers, floats, booleans, and strings.
15.20 HTTP¶
fetch¶
Signature: fetch url : result<str, str>
Fetches content from a URL. Returns Ok body on success, Error message on failure.
match fetch "https://example.com" with
| Ok body -> println body
| Error e -> println $"Failed: {e}"
15.21 Timing¶
time¶
Signature: time { body } -> TimeSpan
Measures the wall-clock execution time of a computation expression. Returns a TimeSpan that can be inspected, formatted, or piped.
15.22 JSON¶
Json.query¶
Signature: Json.query path json -> list<string>
Extracts values from a JSON string using a dotted path with [] for array iteration. Returns a list<string> of all matching leaf values (numeric/boolean values converted to strings). On parse error or missing key, returns an empty list.
Path syntax: - .key — access an object property - [] — iterate array elements - Chained: .key1[].key2 — access key1 (array), iterate elements, access key2 from each
let json = "{\"items\":[{\"name\":\"alpha\"},{\"name\":\"beta\"}]}"
let r = Json.query ".items[].name" json
r |> each println
Pipeline usage:
List append pattern (useful for merging results from multiple JSON files):
15.23 Lazy Evaluation¶
force¶
Signature: force lazy<'T> : 'T
Forces evaluation of a lazy value. On first call, evaluates the deferred expression and caches the result. Subsequent calls return the cached value.
15.24 Lazy Sequences¶
Lazy sequences build on lazy evaluation to create sequences whose elements are computed on demand.
seq { yield ...; yield! ... }¶
Syntax: seq { yield expr; yield! seq_expr }
Creates a lazy sequence. yield produces a single element; yield! splices another sequence.
toList¶
Signature: toList seq<'a> : list<'a>
Forces a lazy sequence into an eagerly-evaluated list.
15.25 Path¶
The Path module provides cross-platform filesystem path utilities.
Path.temporary_directory¶
Signature: Path.temporary_directory -> str
Returns the platform's temporary directory path (e.g. /tmp on Linux, C:\Users\...\AppData\Local\Temp on Windows).
15.26 File I/O¶
The File module provides file operations. Functions that can fail return result<T, str>.
File.open¶
Signature: File.open path mode : result<FileHandle, str>
Opens a file. Mode can be "r" (read), "w" (write/truncate), "a" (append), or "rw" (read/write).
File.close¶
Signature: File.close fd : unit
Closes a file handle.
File.readLine¶
Signature: File.readLine fd : option<str>
Reads one line from the file. Returns None at end of file.
File.readAll¶
Signature: File.readAll path : result<str, str>
Reads the entire file as a string.
File.writeAll¶
Signature: File.writeAll path content : result<unit, str>
Writes a string to a file, creating or truncating it.
File.appendAll¶
Signature: File.appendAll path content : result<unit, str>
Appends a string to a file.
File.size¶
Signature: File.size path : result<int, str>
Returns the file size in bytes.
File.exists¶
Signature: File.exists path : bool
Returns true if the file exists.
File.delete¶
Signature: File.delete path : result<unit, str>
Deletes a file.
15.27 Resource Management¶
let use¶
Syntax: let use name = expr
Binds a disposable resource and automatically calls its dispose function at scope exit (LIFO order). Types with a registered dispose function (such as FileHandle) require either use or manual.
let manual¶
Syntax: let manual name = expr
Binds a disposable resource without automatic cleanup. The user is responsible for calling the dispose function manually. Use when the resource lifetime extends beyond the current scope.
See also: Lists & Collections | Operators & Pipelines | Error Handling | Lazy Evaluation