Haskell:如何评估像“1+2"这样的字符串 [英] Haskell: how to evaluate a String like "1+2"

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

问题描述

实际上我有一些像 "x + y" 这样的公式,它是一个 String.我设法将 x/y 变量替换为特定值,例如 "1.2",它仍然是 String 类型.现在我有像 "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:我想像 read 这样的东西,它可以直接转换整个字符串表达式,而不是逐个处理运算符(+/- 等).那可能吗?

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.

简短的回答是:要评估 Haskell 表达式,其中包括您可能正在谈论的基本数学运算符,只需使用提示"包:

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"

耶!

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

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