Modules and Constants
Pure Functions
No Side Effects
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
call ← square(9)
14integer :: result_15result_ = square(9)16print '(I0)', result_values this stepsquare(9)cally ← 81
6 integer :: y7 y = x * x8end function squarevalues this step81y9xresult_ ← 81
14integer :: result_15result_ = square(9)16print '(I0)', result_values this step81result_print '(I0)', result_
15 result_ = square(9)16 print '(I0)', result_17end program pure_function_demooutput81values this step81result_
Follow the Pure Function
module math_moddefinessquare.square(x)returnsx * x.- The program calls
square(9). result_becomes81.- 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.