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

后端 未结 3 1146
暗喜
暗喜 2020-11-29 07:20

Actually I have some formula like \"x + y\", which is a String. I managed to replace the x/y variable with specific values like

3条回答
  •  一向
    一向 (楼主)
    2020-11-29 07:22

    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!

提交回复
热议问题