Tin

Examples · 8 of 339

08-closures

Functions are values.

examples/08-closures.tintin 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]