I want to create a function composition in Fortran. The idea is if I have f(x) and g(x), I want to find f(g(x)). It is simple in syntax in python Better Function Composition in Python.
Here is a sample Fortran code:
module test10
implicit none
contains
function f5x (x)
real :: f5x
real, intent (in) :: x
f5x = 5.00*x
end function f5x
function f10x (x)
real :: f10x
real, intent (in) :: x
f10x = 10.00*x
end function f10x
end module test10
program call_test10
use test10
implicit none
real :: val1, val2, input
interface
real function fx_new (y)
real, intent (in) :: y
end function fx_new
end interface
input=1.0
write (*,*) 'Invoking f5x'
val1 = f5x(1.0)
write (*,*) val1
write (*,*) 'Invoking f10x'
val1 = f10x(1.0)
write (*,*) val1
write (*,*) 'Invoking f10x(f5x)'
procedure (fx_new), pointer :: ptr1 => f5x
procedure (fx_new), pointer :: ptr2 => f10x
val2 = ptr2(ptr1)
write (*,*) val2
end program call_test10
The statements val1 = f5x(1.0)
and val1 = f10x(1.0)
run by themselves. But when it comes to function composition, I don't know how to achieve that in Fortran. I want to evaluate f10x(f5x) and then want to assign value to x. Any ideas?
If I include a module file and function return type, number of arguments, and type of arguments match, can Fortran compiler decide which function to execute in the included file? Another thing I would like to know is can I get rid of the interface (by using procedure pointer or something else)? The whole idea of interface to execute external functions looks confusing to me, so please suggest a way to execute external functions without interface, if possible. I am aware of keyword external
, but it was meant for much earlier versions (though it continues to work in newer standards).
As procedure pointers are in newer standards (2003, 2008, ...), I would use Fortran standard 2008.