<!-- Closures and pipelines · Tin · https://tin.ad/docs/learn/closures/ · generated from the built page -->

[Learn](https://tin.ad/docs/learn/) · The language · 9 of 34

# Closures and pipelines

**Goal.** Pass functions as values, capture variables in closures, and chain steps with `|>`.

## 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.tin · tin run fn-values.tin*

```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))
}
```

<!-- output -->
```text
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.tin · tin run closure.tin*

```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))
}
```

<!-- output -->
```text
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.tin · tin check capture-var.tin*

```tin
fn main() {
  var rate = 2
  let scale = (x: int) => x * rate
  rate = 10
  print(scale(1))
}
```

<!-- compiler output -->
```text
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.tin · tin run map-filter.tin*

```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))
}
```

<!-- output -->
```text
[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.tin · tin run reduce.tin*

```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)
}
```

<!-- output -->
```text
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.tin · tin run pipe.tin*

```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)))
}
```

<!-- output -->
```text
778
778
```

## Sorting by your own rule

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

*sort-by.tin · tin run sort-by.tin*

```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}")
  }
}
```

<!-- output -->
```text
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`.

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-1.solution.tin · tin run task-1.solution.tin*

```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)
}
```

<!-- output -->
```text
[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).

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-2.solution.tin · tin run task-2.solution.tin*

```tin
fn main() {
  let n = range(1, 11)
    |> filter((x) => x % 2 == 0)
    |> map((x) => x * x)
    |> sum()
  print(n)
}
```

<!-- output -->
```text
220
```

### Task 3: A function that makes functions · harder

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

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-3.solution.tin · tin run task-3.solution.tin*

```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))
}
```

<!-- output -->
```text
10
15
[3, 6, 9]
```

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

## Recap

- A function is a value you can pass and return.
- `map`, `filter` and friends take closures.
- `x |> f |> g` reads left to right.

In the reference: [Closures](https://tin.ad/docs/ref/language/#lambdas) · [Pipelines](https://tin.ad/docs/ref/language/#pipelines) · [map, filter, reduce](https://tin.ad/docs/ref/stdlib/#built-in)
