"Anonymous" functions

Hello, I’m new to fortran and working with some others’ code. I noticed that the code basically stores anonymous functions in scalar variables, which when I see fortran is not supposed to support.

program mwe1
    DOUBLE PRECISION :: f,x
    f(x)= x**2 + 1.0d0

    print *, f(1.0d0),f(2.0d0),f(3.0d0)

end program

This code compiles (gfortran 14.2.0) without warning and outputs:
2.0000000000000000 5.0000000000000000 10.000000000000000

Why does this code work,and what is happening? Is this bad practice or normal? I can’t seem to many other examples using this so I am assuming it’s bad practice.

You have a case of so-called statement functions. They are a rather old feature and actually error-prone and very limited. The modern way is to define internal functions:

program mwe1
    DOUBLE PRECISION :: f,x


    print *, f(1.0d0),f(2.0d0),f(3.0d0)
contains
    f(x)= x**2 + 1.0d0
end program

Such internal functions or subroutines are just as versatile as ordinary routines, but they are only seen within the containing routine or program.

Statement functions consist of a single statement (assignment and expression) only and can be placed in odd locations. Which makes them rather ambiguous when it comes to parsing the code.

2 Likes

Not standard Fortran, I am afraid. Standard Fortran expects an internal-subprogram after a CONTAINS, which is either a function-subprogram or subroutine-subprogram, not a stmt-function-stmt. The standard way would be:

contains
   double precision function f(y)
       double precision :: y
       f = y**2 + 1.0d0
   end function f

But the OP was correct, there are no anonymous functions in Fortran. In Fortran, all procedures are present at compilation, there is no creating subprograms during runtime (like BASIC’s EVAL).

4 Likes

Thank you both. This makes sense now. I will add “removing statement functions” to my refactoring to-do list.

Oh dear, my bad! That happens if you’re too hasty to answer and part of your brain is still busy with other stuff.

1 Like