fn fib(n: int) -> int { if n < 2 { return n; } return fib(n - 1) + fib(n - 2);} for k in 1..=3 { println("tick ${k}");}println("fib(20) = ${fib(20)}");
~/hello $ slangc hello.sl --run
tick 1tick 2tick 3fib(20) = 6765[exit 0]
Functions, ranges and string interpolation.
import "time"; fn hop(id: int, done: chan[int]) { time.sleep(100_000_000); // 100 ms: parks the task, not the thread chan_send(done, id);} let t0 = time.mono();let done: chan[int] = make_chan(10_000);for i in 0..10_000 { spawn hop(i, done);}for i in 0..10_000 { chan_recv(done);}let ms = (time.mono() - t0) / 1_000_000;println("10000 tasks, 100 ms of sleep each: ${ms} ms");
~/tasks $ slangc tasks.sl --run
10000 tasks, 100 ms of sleep each: 490 ms[exit 0]
Ten thousand green tasks. Sleeping parks the task, so they all sleep at once.
// C's atoi says 8080, 80 and 0. slang says:for s in ["8080", "80x80", ""] { let r = to_int(s); guard let n = r else let e = err_of(r) { println(inspect(s) + " -> err: " + e); continue; } println(inspect(s) + " -> " + to_str(n));}
~/errors $ slangc errors.sl --run
"8080" -> 8080"80x80" -> err: not a base-10 integer"" -> err: cannot parse an empty string as int[exit 0]
A bad number is an error you have to look at, not a zero.
import "json"; gc struct Address { city: str, zip: str }gc struct Person { name: str, addr: Address } let body = "{\"name\":\"Ada\",\"addr\":{\"city\":5,\"zip\":\"SW1\"}}";let r: result[Person, str] = json.decode(body);guard let p = r else let e = err_of(r) { println("rejected: " + e); exit(1);}println("hello, " + p.name);
~/json $ slangc json.sl --run
rejected: field 'addr': field 'city': expected a string, got a number[exit 1]
Typed decoding. The error names the exact field path.
struct Box[T] { v: T,} impl Box[T] { fn get(self: Box[T]) -> T { return self.v; } fn doubled(self: Box[T]) -> int { return self.v * 2; }} println(Box { v: 21 }.doubled()); // checked for Box[int]println(Box { v: "hi" }.get()); // doubled never checked here
~/generics $ slangc generics.sl --run
42hi[exit 0]
A method is checked for the types it is called with, and only those.
import "regex";import "log"; let cr = regex.compile("(\\d{4})-(\\d{2})-(\\d{2})");guard let re = cr else let e = err_of(cr) { log.error("bad pattern: " + e); exit(1);}let m = regex.find(re, "due 2026-09-09");println(to_str(m[0]) + ".." + to_str(m[1])); // whole matchprintln(to_str(m[2]) + ".." + to_str(m[3])); // yearregex.free(re);
~/regex $ slangc regex.sl --run
4..144..8[exit 0]
Linear-time matching. No pattern can make it backtrack.