Examples · 4 of 339
04-pipelines
Pipelines and methods.
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