Skip to content

SpecificationVII · Subroutines

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.

Markdown version

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:

UnitCan it have effects?
Subroutine and the main algorithmyes
Functionno: 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);
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.The effect of 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);
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.

In short

  • Function is pure: no input, output or capabilities.
  • Purity is checked through every call.
  • Effects go in Subroutine or in the algorithm.