[Haskell] evaluate function as a string
duncan at coutts.uklinux.net
Thu Apr 22 15:36:32 EDT 2004
On Thu, 2004-04-22 at 13:56, Ay Joselito wrote:
> I am new to Haskell. I want to develop an application
> in which the user enters a mathematical equation,
> presumably as a string (any arbitrary equation, using
> any of the standard mathematical operators : +,*,^,
> etc, and any of the standard functions: sin, exp,
> etc.). I need to take that string, convert it to a
> real function, and evaluate it.
The standard solution would be to define a data structure to represent
your expressions, then write a parser that converts a string into one of
these data structures. Finally you need an evaluation function that
reduces the expression data structure to the final answer.
You could represent your expression using a data type like this:
Data Exp = Number Double
| OpPlus Exp Exp
| OpTimes Exp Exp
| FnSin Exp
... etc ..
If your formulae can contain variables, it will be slightly more
complicated than the above.
You might look at one of the parser combinator libraries to write your
parser, or use the parser generator 'Happy' (which may require using
'Alex' the scanner generator).
Your evaluation function will operate recursively over the structure of
the expression. It will have a case for each expression constructor.
It'll look something like:
eval :: Exp -> Double
eval (Number n) = ...
eval (OpPlus a b) = ...
... etc ...
Hope this points you in the right direction.
More information about the Haskell