相当于Haskell中的python eval [英] Equivalent of python eval in Haskell
问题描述
python中有一个名为 eval
的函数,它接受字符串输入并对其进行评估。
>>> x = 1
>>> print eval('x + 1')
2
>>> print eval('12 + 32')
44
>>>
什么是Haskell相当于 eval
函数?
确实,在Haskell中,就像Java或C ++或类似语言一样,可以调用编译器,然后动态加载代码并执行它。然而,这通常是很重的,几乎从来不会为什么人们在其他语言中使用 eval()
。
eval()
,因为考虑到该语言的功能,对于某些类型的问题,从类似于语言本身的程序输入中构造一个字符串更容易,而不是直接解析和评估输入。 例如,如果您想允许用户在输入字段中输入数字,但在Perl中输入简单的算术表达式或Python,只需在输入中调用 eval()
就比为您希望允许的表达式语言编写解析器要容易得多。不幸的是,这种方法几乎总是导致整体糟糕的用户体验(编译器错误消息不适用于非程序员)并且会打开安全漏洞。在不使用 eval()
的情况下解决这些问题通常涉及到一定程度的代码。在Haskell中,感谢就像 Parsec 一样,编写这些类型的解析器和评估器实际上非常简单的输入问题,并大大消除了对 eval
的渴望。
There is function in python called eval
that takes string input and evaluates it.
>>> x = 1
>>> print eval('x+1')
2
>>> print eval('12 + 32')
44
>>>
What is Haskell equivalent of eval
function?
It is true that in Haskell, as in Java or C++ or similar languages, you can call out to the compiler, then dynamically load the code and execute it. However, this is generally heavy weight and almost never why people use eval()
in other languages.
People tend to use eval()
in a language because given that language's facilities, for certain classes of problem, it is easier to construct a string from the program input that resembles the language itself, rather than parse and evaluate the input directly.
For example, if you want to allow users to enter not just numbers in an input field, but simple arithmetic expressions, in Perl or Python it is going to be much easier to just call eval()
on the input than writing a parser for the expression language you want to allow. Unfortunately, this kind of approach, almost always results in a poor user experience overall (compiler error messages weren't meant for non-programmers) and opens security holes. Solving these problems without using eval()
generally involves a fair bit of code.
In Haskell, thanks to things like Parsec, it is actually very easy to write a parser and evaluator for these kinds of input problems, and considerably removes the yearning for eval
.
这篇关于相当于Haskell中的python eval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!