Haskell:如何评估一个字符串,如“1 + 2” [英] Haskell: how to evaluate a String like "1+2"

查看:131
本文介绍了Haskell:如何评估一个字符串,如“1 + 2”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上我有一些像x + y这样的公式,它是一个 String
我设法将 x / y 变量替换为特定值,例如1.2,它仍然是字符串类型。
现在我的表达式就像1 + 2



所以问题是如何评估一个字符串类型的表达式并得到结果。



ps:我想要像读取,可以直接转换整个字符串表达式而不是处理运算符(+/-等)。那可能吗?

解决方案

您的问题留下了很多解释空间。我猜测你不习惯建立一个完整的lexing,解析,可能的类型检查和评估流程。长的答案会涉及到你定义你想评估哪种语言(只需用'+'整数,或许用'+',' - '''','/'或甚至更大的语言来表示所有的理性)这个简单的答案是:评估Haskell表达式,其中包括您可能正在讨论的基本数学运算符,只需使用提示包:

  $ cabal安装提示
...
$ ghci
> ; import Language.Haskell.Interpreter
> runInterpreter $ setImports [Prelude]>> eval3 + 5
右8

Yay!


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?

解决方案

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!

这篇关于Haskell:如何评估一个字符串,如“1 + 2”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆