This is the mail archive of the fortran@gcc.gnu.org mailing list for the GNU Fortran project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Passing functions to functions


Hi all,

What's the kosher way to pass functions to functions?

For example, consider a function findroot() which implements the
bisection algorithm for finding roots of a real function f : R -> R.
I would like to be able to call it like this:

        ! findroot(f, x1, x2) should be called so that f(x1) < 0.0 < f(x2)
        root = findroot(f, -5.0, 5.0)

        ...

        real function f(x)
                real, intent(in) :: x
                f = sin(2*pi*x) - 2*x
        end function

In GNU Fortran 4.0, I was able to implement this by putting findroot in
a separate module, and defining it like this

        real function findroot(f, x1, x2)
                external f
                real, intent(in) :: x1, x2

                ! the algorithm goes here
        end function

I think this technique is dodgey, since the type of "f" is not declared
anywhere.

Now I'm using GNU Fortran 4.2.  (I got the binaries from a link on the GNU
Fortran wiki.)  It now requires that both findroot() and the argument f()
be in a different module from the one I invoke findroot() from.  If
f() is in the same module as where findroot() is invoked, I get this message

Error: Internal procedure 'f' is not allowed as an actual argument at (1)


So, my questions are:
 * what are all the ways you can pass functions to functions?
 * which ways allow the compiler to provide the most type-safety?
 * is there any difference in terms of how easy it is for the compiler to
make good optimizations?

Thanks,
Andrew


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]