# 7.8 Purity: Function versus Subroutine

> A `Function` only computes: it does not write, read, or touch files or the network. Whatever has effects is declared with `Subroutine`.

Web page: https://pseudolearn.app/en/spec/subprogramas/pureza

> **In one sentence**
>
> A `Function` only computes: it does not write, read, or touch files or the network. Whatever has effects is declared with `Subroutine`.

## 7.8.1 How it works

An **effect** is anything the program does towards the outside: writing to the console, reading from the keyboard, opening a file, asking for the time. PseudoLearn separates two kinds of subprograms:

| Unit | Can it have effects? |
| --- | --- |
| `Subroutine` and the main algorithm | yes |
| `Function` | no: it is **pure** |

A pure function always returns the same result for the same arguments. That makes it easy to test and to understand.

### Program: A function that writes

```pseudolearn
Function r <- Cuadrado(n As Integer)
  Define r As Integer;
  Write "calculando";
  r <- n * n;
EndFunction

Algorithm Principal
  Write Cuadrado(3);
EndAlgorithm
```

**Diagnostics**
- `pureFunctionSideEffect` (error, 1:1): A pure function cannot perform I/O effects or invoke capabilities

*The program finishes with an error.*

The check is **transitive**: a function cannot call a subprogram with effects either, nor one that calls another that has them.

**Figure 7.8-1: An effect that climbs**

Principal calls the function Triple, which calls Avisar, which uses Write. The effect of Write climbs up to Triple, marked as an error.

The effect of `Avisar` climbs up the calls to `Triple`, which is a `Function` and gets rejected.

### Program: An effect hidden in a call

```pseudolearn
Subroutine Avisar()
  Write "aviso";
EndSubroutine

Function r <- Triple(n As Integer)
  Define r As Integer;
  Avisar();
  r <- n * 3;
EndFunction

Algorithm Principal
  Write Triple(3);
EndAlgorithm
```

**Diagnostics**
- `pureFunctionTransitiveSideEffect` (error, 5:1): A pure function cannot invoke subroutines or closures with side effects

*The program finishes with an error.*

The diagnostic points, in order, to every unit in the chain from the first call with an effect to the one that produces it.

> **Limit**
>
> - Where a pure function is expected, a subprogram or closure with effects cannot be passed.
> - If an interface declares a method as `Function`, all its implementations must be pure.
> - A `Function` cannot contain `Await`.

**In short**
- `Function` is pure: no input, output or capabilities.
- Purity is checked through every call.
- Effects go in `Subroutine` or in the algorithm.

**See also**
- [7.1 Declaring subprograms](https://pseudolearn.app/en/spec/subprogramas/declaracion.md)
- [11.4 Effects and capabilities](https://pseudolearn.app/en/spec/tareas/efectos.md)
- [9.5 Interfaces](https://pseudolearn.app/en/spec/objetos/interfaces.md)
