Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: how to evaluate a String like "1+2"

Tags:

haskell

eval

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?

like image 824
yoz Avatar asked Apr 07 '11 14:04

yoz


People also ask

What does ++ mean in Haskell?

The ++ operator is the list concatenation operator which takes two lists as operands and "combines" them into a single list.

What is -> in Haskell?

(->) 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.

Why Haskell is lazy evaluation?

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.

How are expressions evaluated Haskell?

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.


1 Answers

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!

like image 51
Thomas M. DuBuisson Avatar answered Sep 30 '22 08:09

Thomas M. DuBuisson