Fortran 90/95: Read a Function?

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 2K views
NicolasPan
Messages
21
Reaction score
2
Hello everyone! I've been wondering if it is possible in Fortran to 'read' a function.For instance when I code this:
Fortran:
contains
function f(x)
   double precision :: f
   double precision ::x
   f=(whatever the function)
   return
end function
end program
It would be ideal if the program allowed the user to type the function each time, rather than having it pre-set by the programmer.Thanks in advance!
 
Physics news on Phys.org
Fortran is a compiled language. If you need this interpreting feature, you'll have to build a parser or something.
You can have function names as subroutine parameters (look up 'external'), but those functions have to be known and available at link time.
 
To expand on what BvU said, you don't "input" a function. What comes into your program is essentially text, so if the user types "sqrt", your program needs to parse this string to get its semantic meaning; i.e., that you want to call the sqrt() function. Although the string "sqrt" and the function name sqrt appear the same to us, they are very different as far as the program is concerned.
 
You have two options here.
1. You could use a parser/interpreter. Either write one yourself or use an existing one, e.g. http://fparser.sourceforge.net
2. If you need more performance you can also compile the function at runtime. That could for example be done by having your program send code through the Fortran compiler and then execute it. Of course languages with a built in just in time compiler like JavaScript would make this kind of thing a lot easier. JavaScript offers an "eval" function that can compile any code you give it at runtime making it execute a lot faster than any interpreter could.