Fortran

Guide To Learn

A custom operator is essentially a procedure under the hood, with an extended syntax that allows it to be used in expressions much like built-in operators:

result = a .op. b

Once we have a function or a subroutine, it’s straightforward to implement it as a custom operator.

Tip Don’t confuse the custom operator syntax.op. with the logical literal constants .true. or .false.. The latter are reserved words and not operators, and they have periods in them for historical reasons.

These are the naming rules for custom operators:

  • Operator names must be enclosed by periods: .op..
  • Names are restricted to the same character set as variable or procedure names: lower- or uppercase alphabet letters and decimal numbers. Operator names also must not begin with a number.

The main restriction to operators is that they can be either unary, operating on one operand, or binary, operating on two operands. You can’t express procedures that operate on three or more arguments as custom operators.

To make a function available as an operator, we write the same interface as we did for a generic procedure, except that for the name of the operator, we use the word operator, with the operator name in parentheses, as shown in the following listing.

Listing 9.8 Invoking functions with a custom operator

module mod_average
  ...
  public :: operator(.average.)            ❶
  ...
  interface operator(.average.)            ❷
    module procedure :: average_int        ❸
    module procedure :: average_real       ❸
    module procedure :: average_logical    ❸
  end interface average                    ❸
  ...
contains
  ...
end module mod_average

❶ Makes the custom operator publicly accessible

❷ Interface block with the operator name

❸ Specific procedures to be overridden by the operator

As you can see, this is almost identical to what we did with generic procedures. The main difference is the special word operator, which we need to use to specify that the interface is going to be the operator, and not just a procedure.

Writing custom operators

Leave a Reply

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

Scroll to top