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.
ProgramA function that writes
Function r <- Cuadrado(n As Integer)
Define r As Integer;
Write "calculando";
r <- n * n;
EndFunction
Algorithm Principal
Write Cuadrado(3);
EndAlgorithmDiagnostics
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.
Avisar climbs up the calls to Triple, which is a Function and gets rejected.Principal calls the function Triple, which calls Avisar, which uses Write. The effect of Write climbs up to Triple, marked as an error.
ProgramAn effect hidden in a call
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);
EndAlgorithmDiagnostics
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.
In short
Functionis pure: no input, output or capabilities.- Purity is checked through every call.
- Effects go in
Subroutineor in the algorithm.