Pass function as a parameter to another function


I’m having problems trying to pass a function as a parameter to another function

This function

complex function f(x,y)
end function

to the function

complex function g(f,y,x,xf)

            complex function f(s,t)
            end function
        end interface
    end function

using this call

  y = (0.0,1.0)
  result = g(f,y,0.0,5.0)

I’m having this error:

Program received signal SIGSEGV: Segmentation fault - invalid memory reference.

What am I doing wrong?


I think you may not understand the syntax of defining a function. Here is an example.

module m
complex function f(x) result(y)
    real :: x 
    y = cmplx(x,x) ! sets y to a complex number whose real and imaginary
                   ! parts are both x
end function f
end module m
program main
use m
implicit none
real :: x
x = 3.2
end program main

3.20000005 (3.20000005,3.20000005)

The f function is ok. The problem is the way I’m trying to pass it to the g function. In a more general sense I’m just trying to pass a function to another function as a parameter and I don’t know how to do it.

A procedure can have an argument that is a procedure with an interface. Here is an example.

module integral_mod
implicit none
integer, parameter :: wp = kind(1.0d0)
pure function integral(f,a,b,n) result(y)
   pure function f_real_real(x) result(y)
   import wp
   implicit none
   real(kind=wp), intent(in) :: x
   real(kind=wp)             :: y
   end function f_real_real
end interface
procedure(f_real_real) :: f
real(kind=wp), intent(in) :: a,b
integer, intent(in) :: n
real(kind=wp)       :: y
integer             :: i
real(kind=wp)       :: x,h,fsum
h = (b-a)/(n-1)
x = a
fsum = 0.0
do i=1,n
   if (i == 1 .or. i == n) then
      fsum = fsum + f(x)/2
      fsum = fsum + f(x)
   end if
   x = x + h
end do
y = h*fsum
end function integral
end module integral_mod
module funcs_mod
use integral_mod, only: wp
implicit none
pure function square(x) result(y)
real(kind=wp), intent(in) :: x
real(kind=wp)             :: y
y = x**2
end function square
pure function cube(x) result(y)
real(kind=wp), intent(in) :: x
real(kind=wp)             :: y
y = x**3
end function cube
end module funcs_mod

program test_procedure_arg
use integral_mod, only: wp, integral
use funcs_mod   , only: square, cube
implicit none
real(kind=wp) :: a,b
integer       :: n
n = 10**6
a = 0.0_wp
b = 10.0_wp
print "(*(f12.6))", integral(square,a,b,n),integral(cube,a,b,n) 
end program test_procedure_arg

333.333333 2500.000000

1 Like

Thank you! Was what i needed.