Fortran

Guide To Learn

1. Writing reusable code with functions and subroutines

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 ❶ The elemental attribute makes the function compatible with both scalars and arrays. You can now invoke this function with one or more […]

Exercise 1: Modifying state with a subroutine

To modify an input argument in-place, define it with the intent(in out) attribute, as shown in the following listing. Listing 3.21 A subroutine that modifies an input argument in-place ❶ Uses intent(in out) to indicate that a is both an input and an output ❷ We can modify a directly; it will be returned to the calling program or procedure. You […]

Tsunami simulator: Putting it all together

Finally, we get to put together the new function (from subsection 3.2.2) and subroutine (from subsection 3.3.3) in the main program of the tsunami simulator. In a nutshell, this program has the same functionality and behavior as the previous version from chapter 2. The key difference is that now we’ve abstracted away the code to […]

Procedures with optional arguments

Both functions and subroutines can accept optional arguments. These are arguments that may be omitted by the caller, even if they’re specified in the procedure definition. To see optional arguments in action, let’s take our subroutine add from listing 3.13 and add an optional debug input parameter, as shown in listing 3.18. If this parameter is passed by the […]

Writing procedures that operate on both scalars and arrays

When a procedure is defined to operate on scalar arguments, it’s relatively straightforward to make it work with array arguments as well. For example, recall our pure function sum from the previous subsection: Invoking this function as, say, sum(3, 5) will evaluate to 8. Is there a way to pass array arguments to this function such that it returns an array […]

Why are pure functions important?

Including a pure attribute in your function and subroutine statements forces you to write side effect-free code. This has two principal benefits: Tip Write pure procedures whenever possible. As I’ll show you later in the book, using the pure attribute can get you a long way toward functional programming with Fortran.

Some restrictions on pure procedures

A pure procedure, while advantageous from both program design and compiler optimization perspectives, does come with a number of restrictions: There are several more restrictions on pure procedures that are more situational and that you’re less likely to encounter. We’ll revisit this topic later in the book as we encounter these edge cases.

Scroll to top