A pure function promises no side effects and no I/O. The compiler enforces it.

Program

Play the program to square a number with a pure function.

pure_function.f90
Replay: real traced execution (multi-file project)
module math_mod
    implicit none
contains
    pure function square(x) result(y)
        integer, intent(in) :: x
        integer :: y
        y = x * x
    end function square
end module math_mod

program pure_function_demo
    use math_mod
    implicit none
    integer :: result_
    result_ = square(9)
    print '(I0)', result_
end program pure_function_demo
  1. call ← square(9)

    14integer :: result_15result_ = square(9)16print '(I0)', result_
    values this stepsquare(9)call
  2. y ← 81

    6    integer :: y7    y = x * x8end function square
    values this step81y9x
  3. result_ ← 81

    14integer :: result_15result_ = square(9)16print '(I0)', result_
    values this step81result_
  4. print '(I0)', result_

    15    result_ = square(9)16    print '(I0)', result_17end program pure_function_demo
    output81
    values this step81result_

Follow the Pure Function

  1. module math_mod defines square.
  2. square(x) returns x * x.
  3. The program calls square(9).
  4. result_ becomes 81.
  5. The program prints 81. | call | input | result | | --- | --- | --- | | square(9) | 9 | 81 |
pure `pure function` cannot perform I/O or modify globals.
compile check The compiler rejects side effects inside `pure` procedures.
functional style Pure functions are safe to call from elemental and parallel contexts.

Exercise: pure_function.f90

Reproduce the printed value 81, then identify the input value that square multiplies by itself.