Examples
Hello World #
fn main() {
print("Hello, Zolo!")
}
main()
Fibonacci #
fn fibonacci(n: int) -> int {
if n <= 1 { n } else { fibonacci(n - 1) + fibonacci(n - 2) }
}
for i in 0..10 {
print(fibonacci(i))
}
Fibonacci with Memoization #
@memoize
fn fib(n: int) -> int {
if n <= 1 { n } else { fib(n - 1) + fib(n - 2) }
}
print(fib(50)) // instant, thanks to caching
Structs and Methods #
struct Point {
x: f64,
y: f64,
}
impl Point {
fn new(x: f64, y: f64) -> Point {
Point { x, y }
}
fn distance(self) -> f64 {
(self.x ** 2.0 + self.y ** 2.0).sqrt()
}
fn translate(self, dx: f64, dy: f64) -> Point {
Point { x: self.x + dx, y: self.y + dy }
}
}
let p = Point::new(3.0, 4.0)
print(p.distance()) // 5.0
let p2 = p.translate(1.0, 1.0)
print(p2.x) // 4.0
Enums and Pattern Matching #
enum Shape {
Circle(f64),
Rectangle(f64, f64),
Triangle { base: f64, height: f64 },
}
fn area(s: Shape) -> f64 {
match s {
Shape::Circle(r) => 3.14159 * r * r,
Shape::Rectangle(w, h) => w * h,
Shape::Triangle { base, height } => base * height / 2.0,
}
}
let shapes = [
Shape::Circle(5.0),
Shape::Rectangle(3.0, 4.0),
Shape::Triangle { base: 6.0, height: 3.0 },
]
for shape in shapes {
print(area(shape))
}
Pipe Operator #
fn double(x: int) -> int { x * 2 }
fn add_one(x: int) -> int { x + 1 }
fn is_even(x: int) -> bool { x % 2 == 0 }
// Chain transformations
let result = 5
|> double()
|> add_one()
|> double()
print(result) // 22
// With arrays
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let even_squares = numbers
|> Array.filter(|x| x % 2 == 0)
|> Array.map(|x| x * x)
print(even_squares) // [4, 16, 36, 64, 100]
String Interpolation #
let name = "Alice"
let age = 30
print("Hello, {name}!")
print("{name} is {age} years old")
print("In 5 years: {age + 5}")
// With method calls
let items = [1, 2, 3]
print("Count: {Array.len(items)}")
Tagged Templates #
fn sql(parts: [str], id: int) -> str {
"{parts[0]}{id}{parts[1]}"
}
let user_id = 42
let query = sql"SELECT * FROM users WHERE id = {user_id}"
print(query)
Builder Pattern #
@builder
struct Server {
host: str,
port: int,
workers: int,
}
let server = Server.builder()
.host("0.0.0.0")
.port(8080)
.workers(4)
.build()
print("Server at {server.host}:{server.port}")
Testing #
fn add(a: int, b: int) -> int { a + b }
fn multiply(a: int, b: int) -> int { a * b }
@test
fn test_add() {
assert_eq(add(2, 3), 5, "2 + 3 should be 5")
assert_eq(add(-1, 1), 0, "negatives work")
assert_eq(add(0, 0), 0, "zero identity")
}
@test
fn test_multiply() {
assert_eq(multiply(3, 4), 12, "3 * 4 = 12")
assert_eq(multiply(0, 100), 0, "zero property")
}
Run with:
zolo test my_tests.zolo
If Let / While Let #
enum Message {
Text(str),
Number(int),
Quit,
}
let msg = Message::Text("hello")
if let Message::Text(content) = msg {
print("Got text: {content}")
} else {
print("Not a text message")
}
Traits #
trait Describable {
fn describe(self) -> str
}
struct Dog {
name: str,
breed: str,
}
struct Cat {
name: str,
indoor: bool,
}
impl Describable for Dog {
fn describe(self) -> str {
"{self.name} the {self.breed}"
}
}
impl Describable for Cat {
fn describe(self) -> str {
let location = if self.indoor { "indoor" } else { "outdoor" }
"{self.name} ({location} cat)"
}
}
let dog = Dog { name: "Rex", breed: "Labrador" }
let cat = Cat { name: "Whiskers", indoor: true }
print(dog.describe()) // "Rex the Labrador"
print(cat.describe()) // "Whiskers (indoor cat)"
Collections #
// Map
let scores = Map.new()
Map.set(scores, "Alice", 95)
Map.set(scores, "Bob", 87)
Map.set(scores, "Carol", 92)
let keys = Map.keys(scores)
print(keys) // ["Alice", "Bob", "Carol"]
// Set
let unique = Set.from([1, 2, 2, 3, 3, 3])
print(Set.len(unique)) // 3
print(Set.has(unique, 2)) // true
print(Set.to_array(unique)) // [1, 2, 3]
// Iterators
let result = Iter.range(1, 20)
|> Iter.filter(|x| x % 3 == 0)
|> Iter.map(|x| x * x)
|> Iter.collect()
print(result) // [9, 36, 81, 144, 225, 324]
Deprecated Function #
@deprecated("use calculate_v2() instead")
fn calculate(x: int) -> int {
x * 2
}
fn calculate_v2(x: int) -> int {
x * 2 + 1
}
calculate(5) // prints warning once to stderr
For Loop Destructuring #
let pairs = [(1, "one"), (2, "two"), (3, "three")]
for (num, name) in pairs {
print("{num} = {name}")
}
let points = [
Point { x: 1.0, y: 2.0 },
Point { x: 3.0, y: 4.0 },
]
for p in points {
print("({p.x}, {p.y}) -> distance: {p.distance()}")
}