typestar

Modules and use in Fortran

A module and its program in one file: constants and functions behind a name.

! A module is the unit of reuse: data and procedures behind a name.
module tide_tools
    implicit none
    real, parameter :: causeway_limit = 9.5

contains

    pure logical function safe_to_cross(feet)
        real, intent(in) :: feet
        safe_to_cross = feet <= causeway_limit
    end function safe_to_cross
end module tide_tools

! The program pulls the module in with use, then calls as if local.
program modules_use
    use tide_tools, only: safe_to_cross, causeway_limit
    implicit none
    real :: today(3) = [8.2, 11.4, 9.1]
    integer :: i

    print *, "limit is ", causeway_limit, " ft"
    do i = 1, size(today)
        print *, today(i), " ft safe? ", safe_to_cross(today(i))
    end do
end program modules_use

How it works

  1. module tide_tools holds a parameter and, after contains, a pure function.
  2. use tide_tools, only: ... imports exactly the names the program wants.
  3. After use, safe_to_cross calls like a local — the module is the unit of reuse.

Keywords and builtins used here

The run, in numbers

Lines
25
Characters to type
664
Tokens
109
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 101 seconds.

Type this snippet

Step 3 of 3 in Kinds & modules, step 24 of 27 in Language basics.

← Previous Next →