# 3.11 Functions as values

> A subroutine is also a value: it can be stored in a variable, passed as an argument or returned, and called later.

Web page: https://pseudolearn.app/en/spec/tipos/funciones

> **In one sentence**
>
> A subroutine is also a value: it can be stored in a variable, passed as an argument or returned, and called later.

## 3.11.1 How to write it

```pseudolearn
Define «name» As Subroutine(«parameter types») ⟦As «return type»⟧
Subroutine(«parameters») ⟦As «return type»⟧
  «statements»
EndSubroutine
```

```pseudolearn
Define operacion As Subroutine(Integer) As Integer
```
- `Define operacion As`: a variable, declared like any other
- `Subroutine(Integer)`: parameter types, in order
- `As Integer`: type it returns; without this part it returns nothing

## 3.11.2 How it works

The type of a function describes its parameters and its return, for example `Subroutine(Integer) As Integer`. Any subroutine with that shape is a value of that type. A function-typed variable is called as if it were the subroutine itself.

### Program: Storing a subroutine in a variable

```pseudolearn
Subroutine doble(x As Integer) As Integer
  Return x * 2;
EndSubroutine
Subroutine aplicar(f As Subroutine(Integer) As Integer, valor As Integer) As Integer
  Return f(valor);
EndSubroutine
Algorithm Aplicar
  Define operacion As Subroutine(Integer) As Integer <- doble;
  Write operacion(4), " ", aplicar(doble, 10);
EndAlgorithm
```

**Output**

```text
8 20
```

*The program finishes normally.*

## 3.11.3 Anonymous functions and closures

A function can be written in place, without a name: `Subroutine(x As Integer) As Integer … EndSubroutine`. If it uses outside variables, it **captures** them: it takes a copy of their value. That function with its copies is called a **closure**.

### Program: Multiplier factory

```pseudolearn
Subroutine multiplicador(factor As Integer) As Subroutine(Integer) As Integer
  Return Subroutine(x As Integer) As Integer
    Return x * factor;
  EndSubroutine;
EndSubroutine
Algorithm Clausuras
  Define doble As Subroutine(Integer) As Integer <- multiplicador(2);
  Define triple As Subroutine(Integer) As Integer <- multiplicador(3);
  Write doble(5), " ", triple(5);
EndAlgorithm
```

**Output**

```text
10 15
```

*The program finishes normally.*

**Figure 3.11-1: Each closure with its own copy**

The call multiplicador produces two closures, doble and triple. Each carries its own copy of factor inside, 2 and 3 respectively.

Each closure carries its own copy of `factor`. That is why `doble` and `triple` do not interfere.

> **Limit**
>
> - Only variables that are never reassigned after getting their value can be captured: that way the copy and the original cannot diverge.
> - By-reference parameters cannot be captured.
> - Functions are not written, not compared and do not cross between tasks.

> **Common mistakes**
>
> Capturing a variable that changes afterwards is an error, because the closure would see one value and the rest of the program another:
>
> ### Program: Capturing something that changes
>
> ```pseudolearn
> Algorithm CapturaMutable
>   Define n As Integer <- 1;
>   Define f As Subroutine() As Integer <- Subroutine() As Integer
>     Return n;
>   EndSubroutine;
>   n <- 2;
>   Write f();
> EndAlgorithm
> ```
>
> **Diagnostics**
> - `mutableClosureCapture` (error, 4:12): Cannot capture n of type integer: it is reassigned or is a by-reference parameter
>
> *The program finishes with an error.*

> **Under the hood**
>
> A closure is a heap object holding the function's code and an **environment** with the captured copies. The environment outlives the subroutine that created it as long as someone can call the closure, and the collector frees it once nobody can.
>
> **Intermediate representation**
>
> ```text
> module Clausuras en
> class "$environment2" { capture0: i64 }
> func @multiplicador(%0: i64, %1: cell<i64>, %2: cell<str>) -> unit {
> b0() mass 1:
>   stmt.enter @2:3-4:16
>   %3 = const.i64 2 @2:10-4:16
>   %4 = object.new $environment2 @2:10-4:16
>   object.store %4, capture0, %0 @2:10-4:16
>   %5 = value.reinterpret str, %4 @2:10-4:16
>   cell.store %1, %3
>   cell.store %2, %5
>   stmt.exit @2:3-4:16
>   return @2:3-4:16
> }
> func suspendible @main() -> unit {
> b0() mass 3:
>   stmt.enter @7:3-7:69
>   %0 = const.i64 2 @7:67-7:68
>   %1 = cell.local i64 @7:53-7:69
>   %2 = cell.local str @7:53-7:69
>   %3 = call @multiplicador(%0, %1, %2) @7:53-7:69
>   %4 = cell.load_raw %1 @7:53-7:69
>   %5 = cell.load_raw %2 @7:53-7:69
>   stmt.exit @7:3-7:69
>   stmt.enter @8:3-8:70
>   %6 = const.i64 3 @8:68-8:69
>   %7 = cell.local i64 @8:54-8:70
>   %8 = cell.local str @8:54-8:70
>   %9 = call @multiplicador(%6, %7, %8) @8:54-8:70
>   %10 = cell.load_raw %7 @8:54-8:70
>   %11 = cell.load_raw %8 @8:54-8:70
>   stmt.exit @8:3-8:70
>   stmt.enter @9:3-9:33
>   %12 = const.i64 5 @9:15-9:16
>   %13 = call.indirect %4, @__signature0(%5, %12) @9:9-9:17
>   %14 = const.char ' ' @9:19-9:22
>   %15 = const.i64 5 @9:31-9:32
>   %16 = call.indirect %10, @__signature0(%11, %15) @9:24-9:33
>   out.write %13, %14, %16, newline @9:3-9:33
>   stmt.exit @9:3-9:33
>   return @10:1-10:13
> }
> func @$closure2(%0: str, %1: i64) -> i64 {
> b0() mass 2:
>   stmt.enter @1:26-1:32
>   %2 = value.reinterpret obj<"$environment2">, %0 @1:26-1:32
>   %3 = object.load_raw %2, capture0 @1:26-1:32
>   stmt.exit @1:26-1:32
>   stmt.enter @3:5-3:22
>   %4 = int.mul %1, %3 @3:14-3:15
>   stmt.exit @3:5-3:22
>   return %4 @3:5-3:22
> }
> func @__signature0(%0: str, %1: i64) -> i64 {
> b0() mass 0:
>   unreachable
> }
> ```

**In short**
- A subroutine is a value of type `Subroutine(parameters) As return`.
- It can be stored, passed, returned and called.
- An anonymous function captures copies of the variables it uses.
- Only variables that do not change are captured.

**See also**
- [7.1 Declaring subprograms](https://pseudolearn.app/en/spec/subprogramas/declaracion.md)
- [3.12 Generics](https://pseudolearn.app/en/spec/tipos/genericos.md)
