Sn Tin

Learn Tin · Part 1: The language · Chapter 9

Closures and pipelines

Functions as values, and |> to chain them.

Functions are values

You can pass a function to another function, or keep it in a variable. Its type is written like its signature: (int) => int takes an int and returns an int.

fn-values.tintin run fn-values.tin
fn double(x: int): int => x * 2
fn square(x: int): int => x * x

// f is a function that takes an int and returns an int: its type is (int) => int
fn applyTwice(f: (int) => int, x: int): int => f(f(x))

fn main() {
  print(applyTwice(double, 3))
  print(applyTwice(square, 3))
  let op = square                 // a function is a value like any other
  print(op(9))
}
12
81
81

Closures

A closure is a function written inline, without a name: (x) => x + 1. It can use names from where it was written.

closure.tintin run closure.tin
fn main() {
  // (x) => ... is a function without a name: a closure
  let inc = (x: int) => x + 1
  print(inc(41))

  let bonus = 10
  let addBonus = (score: int) => score + bonus   // it can use names from around it
  print(addBonus(80))
}
42
90

A closure copies what it uses at the moment it is made. That is why it can't use a var: if the var changed later, the closure would quietly keep the old value. Tin makes you choose which one you mean:

capture-var.tintin check capture-var.tin
fn main() {
  var rate = 2
  let scale = (x: int) => x * rate
  rate = 10
  print(scale(1))
}
error: closures capture by value, and 'rate' is a `var`
 --> capture-var.tin:3:31
  |
3 |   let scale = (x: int) => x * rate
  |                               ^^^^
  = note: copy it first: `let rateNow = rate`, or pass it as a parameter

The next chapters explain why: everything in Tin is a value, not a reference. Closures follow the same rule.

map, filter and the rest

Most loops over arrays fall into a few patterns, and each one has a function: change every item (map), keep some (filter), ask a question (any, all, count), or find one (find).

map-filter.tintin run map-filter.tin
fn main() {
  let prices = [4.0, 12.5, 7.25, 30.0]
  print(prices.map((p) => p * 1.2))               // change every item
  print(prices.filter((p) => p < 10.0))           // keep some items
  print(prices.any((p) => p > 25.0))
  print(prices.count((p) => p > 5.0))
  print(prices.find((p) => p > 10.0))
}
[4.8, 15.0, 8.7, 36.0]
[4.0, 7.25]
true
3
Some(12.5)

reduce is the general one. It carries a value from item to item:

reduce.tintin run reduce.tin
fn main() {
  let words = ["tin", "is", "small"]
  // reduce walks the array, carrying a running value: here, the total length
  let letters = words.reduce(0, (total, w) => total + w.len)
  print(letters)
  let longest = words.reduce("", (best, w) => if w.len > best.len { w } else { best })
  print(longest)
}
10
small

Pipelines with |>

x |> f(y) means f(x, y). It lets you write a chain of steps in the order they happen, instead of inside out:

pipe.tintin run pipe.tin
fn main() {
  let orders = [12, 250, 40, 8, 99]

  // x |> f(y) means f(x, y). Read it top to bottom, like a recipe.
  let bigTotal = orders
    |> filter((n) => n >= 40)
    |> map((n) => n * 2)
    |> sum()
  print(bigTotal)

  // the same thing, nested inside out:
  print(sum(map(filter(orders, (n) => n >= 40), (n) => n * 2)))
}
778
778

Sorting by your own rule

sortBy takes a closure that says whether a comes before b:

sort-by.tintin run sort-by.tin
type Player = { name: string, score: int }

fn main() {
  let players = [
    Player { name: "Ada", score: 72 },
    Player { name: "Bo", score: 95 },
    Player { name: "Cy", score: 88 },
  ]
  // sortBy takes a function that says whether a comes before b
  let ranked = sortBy(players, (a, b) => a.score > b.score)
  for i, p in ranked {
    print("{i + 1}. {p.name} {p.score}")
  }
}
1. Bo 95
2. Cy 88
3. Ada 72

Tasks

●○○ Task 1: Convert them all

Turn [12.0, 19.5, 23.0, 31.5, 8.0] (Celsius) into Fahrenheit with one map.

Solution
task-1.solution.tintin run task-1.solution.tin
fn main() {
  let temps = [12.0, 19.5, 23.0, 31.5, 8.0]
  let fahrenheit = temps.map((c) => c * 9 / 5 + 32)
  print(fahrenheit)
}
[53.6, 67.1, 73.4, 88.7, 46.4]

●●○ Task 2: A pipeline

Using range(1, 11), |>, filter, map and sum, add up the squares of the even numbers from 1 to 10 (the answer is 220).

Solution
task-2.solution.tintin run task-2.solution.tin
fn main() {
  let n = range(1, 11)
    |> filter((x) => x % 2 == 0)
    |> map((x) => x * x)
    |> sum()
  print(n)
}
220

●●● Task 3: A function that makes functions

Write multiplier(by: int): (int) => int, so that multiplier(3) returns a function that triples its argument.

Solution
task-3.solution.tintin run task-3.solution.tin
// Returns a function. Each one remembers its own `by`.
fn multiplier(by: int): (int) => int => (x: int) => x * by

fn main() {
  let double = multiplier(2)
  let triple = multiplier(3)
  print(double(5))
  print(triple(5))
  print([1, 2, 3].map(triple))
}
10
15
[3, 6, 9]

The returned closure copied by when it was made. double and triple each carry their own copy.

What's next

Next: Generics. One function or type for many element types.

In the reference: Closures · Pipelines · map, filter, reduce