Skip to content

SpecificationIII · Types and values

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.

Markdown version

3.11.1 How to write it

Define «name» As Subroutine(«parameter types») ⟦As «return type»⟧
Subroutine(«parameters») ⟦As «return type»⟧
  «statements»
EndSubroutine
  1. Define operacion Asa variable, declared like any other
  2. Subroutine(Integer)parameter types, in order
  3. As Integertype 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.

ProgramStoring a subroutine in a variable

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

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.

ProgramMultiplier factory

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

10 15

The program finishes normally.

Figure 3.11-1.Each closure carries its own copy of factor. That is why doble and triple do not interfere.

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

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.