Code Examples
Real examples demonstrating ilusm's capabilities for practical applications.
For tiny per-module programs with recorded interpreter output, see Domain snippets.
HTTP Server
Raw HTTP server using net.tcp_listen and net.serve with route handlers:
use net
use jsn
routes = [
{mtd: "GET", pat: "/", fn: \(req, prm) {c: 200, bod: "Welcome to ilusm"}},
{mtd: "GET", pat: "/api/users", fn: \(req, prm)
users = [{id: 1, nam: "Alice"}, {id: 2, nam: "Bob"}]
{c: 200, bod: jsn.enc(users)}},
{mtd: "POST", pat: "/api/users", fn: \(req, prm)
data = jsn.dec(req.body)
{c: 201, bod: jsn.enc({id: 3, nam: data.nam})}}
]
lsn = net.tcp_listen(":8080")
prn("listening on :8080")
net.serve(lsn, routes, 8192, 65536, 5000)
API Client
HTTP client with error handling:
use net
use jsn
# simple GET
res = net.get("https://api.example.com/users")
if res.status == 200:
users = jsn.dec(res.body)
prn $"fetched {len(users)} users"
# POST with JSON body
body = jsn.enc({nam: "Charlie", eml: "charlie@example.com"})
res = net.post("https://api.example.com/users", body)
if res.status == 201:
usr = jsn.dec(res.body)
prn $"created user: {usr.nam}"
| prn $"error: HTTP {res.status}"
# GET with custom headers
res = net.get_hdr("https://api.example.com/me", {Authorization: "Bearer tok123"})
if res.status == 200: prn(jsn.dec(res.body))
Data Processing Pipeline
Transform and filter data using pipelines and trl:
use fs
use jsn
use trl
# load records from JSON file
raw = jsn.dec(fs.rd("data/sales.json"))
prn $"loaded {len(raw)} records"
# validation and enrichment functions
valid(r) = r.prc > 0 and r.qty > 0
enrich(r) =
tot = r.prc * r.qty
tax = tot * 0.08
{id: r.id, prc: r.prc, qty: r.qty, tot: tot, tax: tax, grd: tot + tax}
# pipeline: filter valid, enrich
result = trl.map(trl.fil(raw, valid), enrich)
prn $"valid records: {len(result)}/{len(raw)}"
# write output
fs.wr("data/processed.json", jsn.enc(result))
prn "done"
CLI Tool
Command-line tool with argument handling:
use os
use fs
use jsn
use txt
use trl
# osarg() returns the full argv list (bare fn loaded by `use os`)
argv = osarg()
path = if argv != nil and len(argv) > 0: argv[0] | nil
if path == nil:
prn("usage: ilusm run tool.ilu <file> [--fmt json|csv]")
osext(1)
fmt = if argv != nil and len(argv) > 1: argv[1] | "json"
# check file exists
if !fs.has(path):
prn($"file not found: {path}")
osext(1)
# read and parse
content = fs.rd(path)
data = jsn.dec(content)
prn $"loaded {len(data)} items from {path}"
# process
result = trl.map(
trl.fil(data, \(x) x.active == tru),
\(x) {nam: x.nam, val: x.val})
prn $"active items: {len(result)}"
# output
if fmt == "json":
prn(jsn.enc(result))
| if fmt == "csv":
prn "nam,val"
i = 0
whl i < len(result):
prn $"{result[i].nam},{result[i].val}"
i = i + 1
| prn $"unknown format: {fmt}"
File Processor
Read, transform, and write files with concurrency:
use fs
use txt
use trl
use syn
use tim
# list files in a directory
dir = "data"
entries = fs.ls(dir)
prn $"found {len(entries)} entries"
# process each file
process(path) =
content = fs.rd(path)
lines = txt.spl(content, "\n")
nonempty = trl.fil(lines, \(l) len(l) > 0)
{path: path, lines: len(lines), nonempty: len(nonempty)}
# concurrent processing with syn.run
ch = syn.chan()
i = 0
whl i < len(entries):
path = $"{dir}/{entries[i]}"
if fs.ex(path):
syn.run(\() ch.snd(process(path)))
i = i + 1
# collect results
results = []
i = 0
whl i < len(entries):
r = try(\() ch.rcv())
if r.err == nil: results = trl.cat(results, [r.val])
i = i + 1
total = trl.red(results, 0, \(a, r) a + r.lines)
prn $"processed {len(results)} files, {total} total lines"
JSON API Service
RESTful JSON API using net.tcp_listen and net.serve:
use net
use jsn
use trl
users = [{id: 1, nam: "Alice", eml: "alice@example.com"},
{id: 2, nam: "Bob", eml: "bob@example.com"}]
nxt = 3
json_hdr = {"content-type": "application/json"}
routes = [
{mtd: "GET", pat: "/api/users", fn: \(req, prm)
{c: 200, hdr: json_hdr, bod: jsn.enc(users)}},
{mtd: "GET", pat: "/api/users/:id", fn: \(req, prm)
uid = int(prm.id)
matches = trl.fil(users, \(u) u.id == uid)
if len(matches) > 0:
{c: 200, hdr: json_hdr, bod: jsn.enc(matches[0])}
| {c: 404, bod: "not found"}},
{mtd: "POST", pat: "/api/users", fn: \(req, prm)
data = jsn.dec(req.body)
nu = {id: nxt, nam: data.nam, eml: data.eml}
nxt = nxt + 1
users = trl.cat(users, [nu])
{c: 201, hdr: json_hdr, bod: jsn.enc(nu)}},
{mtd: "DELETE", pat: "/api/users/:id", fn: \(req, prm)
uid = int(prm.id)
users = trl.fil(users, \(u) u.id != uid)
{c: 204, bod: ""}}
]
lsn = net.tcp_listen(":3000")
prn("API running on :3000")
net.serve(lsn, routes, 8192, 65536, 5000)
Tips
- Use trl - chain
trl.map,trl.fil,trl.redfor clean data transforms - Prefer
$"..."- interpolated strings are cleaner than concatenation - Error handling - wrap risky 0-arg calls with
try(f)→{val, err} - Concurrency - use
syn.runfor tasks andsyn.chanfor message passing - Tracing - wrap blocks with
trc "name":for automatic timing - Short names - ilusm stdlib uses ≤5-letter names:
trl,jsn,txt,enc,rex