Search code examples
haskelleval

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


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?


Solution

  • 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!