Actually I have some formula like "x + y"
, which is a String
.
I managed to replace the x/y
variable with specific values like "1.2"
, which is still String
type.
Now I have expression like "1 + 2"
.
So the problem is how to evaluate a expression of a string type and get the result.
ps: I wanna sth like read
, that can directly convert the whole string expression instead of handling the operator (+/-,etc) case by case. Is that possible?
The ++ operator is the list concatenation operator which takes two lists as operands and "combines" them into a single list.
(->) is often called the "function arrow" or "function type constructor", and while it does have some special syntax, there's not that much special about it. It's essentially an infix type operator. Give it two types, and it gives you the type of functions between those types.
Haskell is a lazy language. It does not evaluate expressions until it absolutely must. This frequently allows our programs to save time by avoiding unnecessary computation, but they are at more of a risk to leak memory. There are ways of introducing strictness into our programs when we don't want lazy evaluation.
The order of evaluation in Haskell is determined by one and only one thing: Data Dependence. An expression will only be evaluated when it is needed, and will not be evaluated if it is not needed.
Your question leaves a lot of room for interpretation. I'm taking a guess you aren't accustom to building a whole pipeline of lexing, parsing, maybe type checking, and evaluating. The long answer would involve you defining what language you wish to evaluate (Just integers with '+', perhaps all rationals with '+', '-' '*', '/', or even a larger language?) and perform each of the above steps for that language.
The short answer is: to evaluate Haskell expressions, which includes the basic math operators you're probably talking about, just use the "hint" package:
$ cabal install hint
...
$ ghci
> import Language.Haskell.Interpreter
> runInterpreter $ setImports ["Prelude"] >> eval "3 + 5"
Right "8"
Yay!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With