Chapter 4: Functions as values

Secrets

  • closures
  • function types

Functions are values. secret_add(2) returns a new function that remembers n; that is a closure.

The return type fn (x: Int) -> Int spells out "a function from Int to Int". secret_combine takes two of them and pipes a value through both.

Open in playground
def secret_add(n: Int) -> fn (x: Int) -> Int {
  fn(x) {n + x}
}

def secret_subtract(n: Int) -> fn (x: Int) -> Int {
  fn(x) {x - n}
}

def secret_multiply(n: Int) -> fn (x: Int) -> Int {
  fn(x) {x * n}
}

def secret_divide(n: Int) -> fn (x: Int) -> Int {
  fn(x) {x / n}
}

def secret_combine(f1: fn(Int) -> Int, f2: fn(Int) -> Int) -> fn(Int) -> Int {
  fn(x) {
    x
    |> f1()
    |> f2()
  }
}

pub def main() {
  adder = secret_add(2)
  subtractor = secret_subtract(2)
  multiplier = secret_multiply(7)
  divider = secret_divide(3)
  combined = secret_combine(multiplier, divider)
  echo [adder(2), subtractor(3), combined(6)]
}

An exercism exercise from the Gleam track, solved in Bea: beacode/src/e13_secrets.bea