Elemental functions in Fortran
Write the conversion for one value; elemental maps it over arrays for free.
program elemental_functions
implicit none
real :: celsius(5) = [12.0, 18.5, 24.0, 31.5, 8.0]
! Written for one value, elemental maps it over whole arrays.
print *, "one reading: ", to_fahrenheit(20.0)
print *, "all readings: ", to_fahrenheit(celsius)
contains
elemental real function to_fahrenheit(c)
real, intent(in) :: c
to_fahrenheit = c * 9.0 / 5.0 + 32.0
end function to_fahrenheit
end program elemental_functions
How it works
elemental real function to_fahrenheit(c)is written for a single reading.- Called with a scalar it returns a scalar, as usual.
- Called with
celsius, the whole array converts in one expression.
Keywords and builtins used here
containselementalendfunctionimplicitintentnoneprintprogramreal
The run, in numbers
- Lines
- 15
- Characters to type
- 422
- Tokens
- 72
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 66 seconds.
Step 3 of 3 in Procedures, step 15 of 27 in Language basics.