9 Generic procedures and operators for any data type

 

This chapter covers

  • Writing generic procedures that work on any data type
  • Using custom operators for cleaner code
  • Redefining built-in operators

Every useful computer program takes some input data, performs a number of operations on that data, and outputs the results. The data that the program works with is stored in variables of various types. Different languages handle different types with different strictness. Fortran, being a strongly typed language, is quite strict about how you pass input arguments to functions and subroutines. Specifically, the data types of arguments between the procedure invocation and definition must match, or else the compiler will abort with an error message. This strong typing discipline has its pros and cons. On the one hand, it can be tedious to have to write the same procedure for multiple different data types. On the other hand, Fortran’s strong typing pushes you to write correct and robust code. Fortunately, Fortran provides a mechanism to use the same procedure name to invoke different specific procedures that operate on different data types. This mechanism is the generic procedure, which is also the main topic of this chapter.

9.1 Analyzing weather data of different types

9.1.1 About the data

9.1.2 Objectives

9.1.3 Strategy for this exercise

9.2 Type systems and generic procedures

9.2.1 Static versus strong typing

9.3 Writing your first generic procedure

9.3.1 The problem with strong typing

9.3.2 Writing the specific functions

9.3.3 Writing the generic interface

9.3.4 Results and complete program

9.4 Built-in and custom operators

9.4.1 What’s an operator?

9.4.2 Things to do with operators

9.4.3 Fortran’s built-in operators

9.4.4 Operator precedence

9.4.5 Writing custom operators

9.4.6 Redefining built-in operators