Fortran

Guide To Learn

Exercise 2: Writing an elemental function that operates on both scalars and arrays

The solution is to add the pure elemental attributes to our previous version of the cold front program, as shown in the following listing.

Listing 3.22 Cold front temperature function that works with scalars and arrays

real pure elemental function cold_front_temperature( &
  temp1, temp2, c, dx, dt) result(r)                     ❶
  real, intent(in) :: temp1, temp2, c, dx, dt
  r = temp2 - c * (temp2 - temp1) / dx * dt
end function cold_front_temperature

❶ The elemental attribute makes the function compatible with both scalars and arrays.

You can now invoke this function with one or more input arguments being arrays of any number of dimensions; for example

print *, cold_front_temperature(12., 24., [15., 20., 25.], 960., 24.)

Keep in mind that if more than one of the input arguments are arrays, they have to be of the same shape and size. The pure attribute isn’t required because elemental implies pure by default; however, I included it for clarity. Either of these attributes must appear after the type attribute (real) and before the function or subroutine statement.

Exercise 2: Writing an elemental function that operates on both scalars and arrays

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top