Passing array valued functions as argument to function.

From: andy2o (andy2O_at_hotmail.com)
Date: 11/19/04


Date: 19 Nov 2004 05:51:53 -0800

Hi all,

I've spent several years working with Fortran 95, yet somehow I've
never needed to write functions which use other functions as arguments
until today. I've struggled to make sense of this from the books I
have to hand (no M&R just now).

The purpose of the code will be to compute a definite integral of the
passed function. Here's a toy code example of what I naively expected
to work:

MODULE one
CONTAINS
  FUNCTION f1(x_in) RESULT (y_out)
    DOUBLE PRECISION :: x_in(:)
    DOUBLE PRECISION :: y_out(SIZE(x_in))
    y_out = 2*x_in
  END FUNCTION f1
END MODULE one

PROGRAM test
  USE one
  DOUBLE PRECISION :: a(3)=(/ 1.0d0,2.0d0,3.0d0 /)
  PRINT*, f1(a)
  PRINT*, eval(a,f1)

CONTAINS
  FUNCTION eval(x_in,func) RESULT (y_out)
    DOUBLE PRECISION :: x_in(:)
    DOUBLE PRECISION :: y_out(SIZE(x_in))
    DOUBLE PRECISION, EXTERNAL :: func
    
    y_out = func(x_in)
  END FUNCTION eval
END PROGRAM test

but I get:

bash$ f95 test.f90 #(Note f95=Nag's compiler on linux.)
Error: test.f90, line 14: Array supplied for scalar argument FUNC (no.
2) of EVAL
[f95 error termination]

Could someone explain how this is meant to be done in Fortran 95.
Many thanks,
Yours,
andy.

PS:
I'd also much appreciate an explanation of why when I replace the
function f1 with

  FUNCTION f1(x_in) RESULT (y_out)
    DOUBLE PRECISION :: x_in(:)
    DOUBLE PRECISION :: y_out
    y_out = 2*x_in(1)
  END FUNCTION f1

the code segfaults instead.



Relevant Pages

  • Re: double precision difference between matlab and fortran 90
    ... I have a variable 'alpha', ... The question that remains is why does fortran print 0.999999999999999 ... end program test ... calculation carried out by the CVF compiler is rounded to nearest value and ...
    (comp.lang.fortran)
  • Re: overload array index operator
    ... >> Is there any way to overload the index operator in fortran? ... > end subroutine repoint ... > end program test ...
    (comp.lang.fortran)
  • Read/Write Matlab files in fortran
    ... I'm starting to write a fortran 90 interface to a C library I wrote to ... read/write matlab files. ... INTEGER,DIMENSION:: dims ... END PROGRAM test ...
    (comp.lang.fortran)
  • Re: Version detection fails
    ... implicit none ... recursive subroutine aux ... end program test ... IntelFortran Compiler for IntelEM64T-based applications, ...
    (comp.lang.fortran)
  • Fortran 90 MAT FIle I/O module
    ... Rather new to fortran 90. ... I have gotten some of it to compile with ... malloc/calloc routines since those calls get wrapped through the g95 ... END PROGRAM test ...
    (comp.soft-sys.matlab)