In Fortran, is that possible to link an integer to a procedure (a subroutine or a function)?

84 views Asked by At

I am writing a Fortran program to solve Euler Project problems. In my implementation each problem is a function, for example:

character(len=20) function euler_problem_0001()
    use some_external_lib
    ...
end function euler_problem_0001

and if I print the function I simply get the answer.

print *, euler_problem_0001()

Now I have finished quite a few problems and I find it a bit tedious to write print *, euler_problem_xxxx() over and over again. So my questions is: Is there a way that I can construct a derived type that could link an integer (number of the problem) with the actual procedure? Something like

type, public :: int_to_proc
    character(len=:) :: proc_name 
    procedure(proc_x), pointer :: proc_p 
end type int_to_proc

so that if I initialize the type with an integer,

call int_to_proc%init(2)

then the type bound procedure pointer will point to the function euler_problem_0002(). In this case I only have to write a loop similar to this

type(int_to_proc) :: prob

do i = 1, 500
    call prob%init(i)
    print *, prob%proc_p()
end do 

instead of writing 500 lines of print *, euler_problem_xxxx(). Also, any work-around is also welcome. Thanks!

0

There are 0 answers