Chapter 4 of 8
Functions, pipelines and closures
x |> f(y) means f(x, y), and so does x.f(y). Use whichever reads better.
tin run examples/04-pipelines.tin// Pipelines and methods.
// x |> f(y) means f(x, y)
// x.f(y) means f(x, y) too — use whichever reads better.
type Employee = { name: string, team: string, salary: int }
fn main() {
let staff = [
Employee { name: "Ada", team: "compilers", salary: 180 },
Employee { name: "Grace", team: "compilers", salary: 210 },
Employee { name: "Linus", team: "kernel", salary: 190 },
Employee { name: "Margaret", team: "flight", salary: 230 },
Employee { name: "Dennis", team: "kernel", salary: 170 },
]
// pipeline style
let payroll = staff |> map(e => e.salary) |> sum
print("payroll: {payroll}")
// method style
let compilers = staff.filter(e => e.team == "compilers").map(e => e.name)
print("compilers team: {compilers.join(", ")}")
// mix them
let top = staff
|> sortBy((a, b) => a.salary > b.salary)
|> map(e => "{e.name} ({e.salary})")
print("by salary: {top.slice(0, 3).join(" > ")}")
let squares = range(1, 6) |> map(n => n * n)
print(squares)
print(squares |> reduce(0, (acc, n) => acc + n))
print("any over 20? {squares.any(n => n > 20)}")
print("all even? {squares.all(n => n % 2 == 0)}")
print("first over 5: {squares.find(n => n > 5)}")
let shout = "the quick brown fox".split(" ") |> map(w => w.upper()) |> join(" ")
print(shout)
} payroll: 980
compilers team: Ada, Grace
by salary: Margaret (230) > Grace (210) > Linus (190)
[1, 4, 9, 16, 25]
55
any over 20? true
all even? false
first over 5: Some(9)
THE QUICK BROWN FOX Functions are values. Lambdas capture the variables they use by value, so a closure can't change something behind your back.
tin run examples/08-closures.tin// Functions are values. Lambdas capture the variables they use, by value.
fn adder(n: int): (int) => int => x => x + n
fn compose(f: (int) => int, g: (int) => int): (int) => int => x => g(f(x))
fn twice(f: (int) => int): (int) => int => compose(f, f)
type Button = { label: string, onClick: () => string }
fn double(x: int): int => x * 2
fn main() {
let add5 = adder(5)
print(add5(10))
// named functions are values too
let pipeline = compose(double, add5)
print(pipeline(10))
print(twice(twice(double))(1))
// closures stored in data
let user = "Ada"
let buttons = [
Button { label: "greet", onClick: () => "hello, {user}" },
Button { label: "shout", onClick: () => user.upper() + "!" },
]
for b in buttons {
print("{b.label}: {b.onClick()}")
}
// a table of operations
let ops = [adder(1), adder(10), double, x => x * x]
print(ops.map(f => f(7)))
} 15
25
16
greet: hello, Ada
shout: ADA!
[8, 17, 14, 49]