← Back to Blog

The Standard Library

July 15, 2025 languagestdlib

Lateralus ships with 120+ standard library functions covering collections, I/O, text processing, networking, and more. Everything is designed for pipeline composition.

◉ Module Overview

◉ Collections

All collections have pipeline-friendly APIs:

import collections

// Vec (dynamic array)
let numbers = vec_new()
numbers |> push(1) |> push(2) |> push(3)
let doubled = numbers |> map(fn(x) { x * 2 })

// Map (hash map)
let scores = map_new()
scores["alice"] = 100
scores["bob"] = 85
scores |> entries() |> filter(fn(e) { e.value > 90 })

// Set (unique values)
let tags = set_from(["rust", "go", "lateralus"])
tags |> contains("lateralus")  // true

// Queue (FIFO)
let q = queue_new()
q |> enqueue(1) |> enqueue(2)
let first = q |> dequeue()  // Some(1)

◉ Pipeline Functions

Core functions that work with any iterable:

// Transform
map(items, fn)           // Transform each element
filter(items, pred)      // Keep matching elements
flat_map(items, fn)      // Map and flatten

// Reduce
fold(items, init, fn)    // Reduce to single value
reduce(items, fn)        // Reduce without init
sum(items)               // Sum numbers
product(items)           // Multiply numbers

// Access
first(items)             // First element (Option)
last(items)              // Last element (Option)
nth(items, n)            // Nth element (Option)
take(items, n)           // First n elements
drop(items, n)           // Skip n elements

// Predicates
any(items, pred)         // True if any match
all(items, pred)         // True if all match
none(items, pred)        // True if none match
find(items, pred)        // First matching (Option)

// Ordering
sort(items)              // Sort naturally
sort_by(items, key_fn)   // Sort by key
reverse(items)           // Reverse order
unique(items)            // Remove duplicates

// Grouping
group_by(items, key_fn)  // Group into map
partition(items, pred)   // Split into two
chunk(items, n)          // Split into chunks
zip(a, b)                // Pair elements

◉ I/O

Streaming file and network I/O:

import io

// Read file
let content = read_file("data.txt")?
let lines = read_lines("data.txt")
    |> filter(fn(line) { !line.is_empty() })
    |> collect()

// Write file
write_file("out.txt", "Hello")?
append_file("log.txt", "Entry\n")?

// Stream processing (lazy)
read_lines("huge.txt")
    |> filter(fn(l) { l.starts_with("ERROR") })
    |> take(100)
    |> collect()  // Only reads until 100 found

// Binary I/O
let bytes = read_bytes("image.png")?
write_bytes("copy.png", bytes)?

◉ Strings

import strings

// Basic operations
upper("hello")           // "HELLO"
lower("HELLO")           // "hello"
trim("  hi  ")           // "hi"
split("a,b,c", ",")      // ["a", "b", "c"]
join(["a", "b"], "-")    // "a-b"

// Testing
starts_with("hello", "he")   // true
ends_with("hello", "lo")     // true
contains("hello", "ell")     // true

// Transform
replace("hello", "l", "L")   // "heLLo"
replace_first("hello", "l", "L")  // "heLlo"

// Pipeline-style
"  Hello, World!  "
    |> trim()
    |> lower()
    |> replace(",", "")
    |> split(" ")
// ["hello", "world!"]

◉ Math

import math

// Basic
abs(-5)          // 5
min(3, 7)        // 3
max(3, 7)        // 7
clamp(15, 0, 10) // 10

// Rounding
floor(3.7)       // 3.0
ceil(3.2)        // 4.0
round(3.5)       // 4.0
trunc(3.9)       // 3.0

// Powers and roots
sqrt(16.0)       // 4.0
pow(2.0, 10.0)   // 1024.0
log(100.0, 10.0) // 2.0
ln(E)            // 1.0

// Trigonometry
sin(PI / 2.0)    // 1.0
cos(0.0)         // 1.0
tan(PI / 4.0)    // 1.0
atan2(1.0, 1.0)  // PI / 4

◉ JSON

import json

// Parse
let data = json_parse('{"name": "Alice", "age": 30}')?

// Access
data["name"]     // "Alice"
data["age"]      // 30

// Serialize
let obj = { "items": [1, 2, 3], "active": true }
let str = json_stringify(obj)
// '{"items":[1,2,3],"active":true}'

// Pretty print
json_stringify_pretty(obj, indent=2)

◉ Time

import time

// Current time
let now = now()
let today = today()

// Create
let dt = datetime(2025, 7, 15, 14, 30, 0)
let d = date(2025, 7, 15)

// Format
format(now, "%Y-%m-%d %H:%M:%S")  // "2025-07-15 14:30:00"
format(today, "%B %d, %Y")        // "July 15, 2025"

// Parse
parse_datetime("2025-07-15", "%Y-%m-%d")?

// Arithmetic
now + duration_hours(2)
now - duration_days(1)
now.add_months(3)

◉ HTTP

import http

// GET request
let response = http_get("https://api.example.com/data")?
let data = response.json()?

// POST request
let response = http_post(
    "https://api.example.com/users",
    headers: { "Content-Type": "application/json" },
    body: json_stringify({ "name": "Alice" })
)?

// Pipeline-style API fetching
http_get("https://api.example.com/users")?
    |> json()?
    |> get("data")
    |> filter(fn(u) { u["active"] })
    |> map(fn(u) { u["email"] })

◉ Async

import async

// Concurrent tasks
let results = await_all([
    fetch_user(1),
    fetch_user(2),
    fetch_user(3),
])

// With timeout
let result = with_timeout(
    fetch_data(),
    duration_seconds(5)
)?

// Channels
let (tx, rx) = channel()
spawn(fn() { tx.send("hello") })
let msg = rx.recv()?

◉ Importing Modules

// Import entire module
import math
math.sqrt(4.0)

// Import specific functions
from math import sqrt, pow
sqrt(4.0)

// Import all
from strings import *
upper("hello")

// Alias
import json as j
j.parse("{}")

Full stdlib documentation at github.com/bad-antics/lateralus-lang/stdlib.