Haskell: how to evaluate a String like “1+2”

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 ‘+’, ‘-‘ ‘*’, “https://stackoverflow.com/”, 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!

Leave a Comment