Reputation: 75
This is normal definition of some function as I know:
real function f(x)
real x
f = (sin(x))**2*exp(-x)
end function f
But I want to define a function from some string, for example the program will ask me to write it, and then it will define the function f in a program. Is this possible in Fortran?
Upvotes: 4
Views: 232
Reputation: 18098
I worked on a project once that tried to achieve something similar. We read in a string that contained a string with named variables and mathematical operations (a function if you will). In this string the variables then got replaced by their numerical values and the terms were evaluated.
The basic idea is not to too difficult, but it requires a lot of string manipulations - and it is not a function
in the context of a programming language.
We did it like this:
+
,-
,/
,*
, but remember to honor bracketscos
? Yes => recurse into argumentsThis works quite well, but it requires:
This is not trivial to do in Fortran, so if you have other options (like calling an external tool/script that returns the value), I would look into that - especially if you are new to Fortran!
Upvotes: 1
Reputation: 6241
What you are looking for is possible in reflective programming languages, and is not possible in Fortran.
Quote from the link above:
A language supporting reflection provides a number of features available at runtime that would otherwise be very obscure to accomplish in a lower-level language. Some of these features are the abilities to:
Discover and modify source code constructions (such as code blocks, classes, methods, protocols, etc.) as a first-class object at runtime.
Convert a string matching the symbolic name of a class or function into a reference to or invocation of that class or function.
Evaluate a string as if it were a source code statement at runtime.
Create a new interpreter for the language's bytecode to give a new meaning or purpose for a programming construct.
Upvotes: 4