简体   繁体   English

在Prolog中评估字符串

[英]Evaluating a String in Prolog

In prolog I have a string that needs to be evaluated, for example: 在序言中,我有一个字符串需要评估,例如:

X = '4+2/5'

Is there a way to convert or parse this string into an expression to be evaluated? 有没有办法将此字符串转换或解析为要求值的表达式?

Something like: 就像是:

?- String_Eval('4+2/5', Result).
Result = 4.4.

Using SWI-Prolog 6.6.6. 使用SWI-Prolog 6.6.6。

Thanks 谢谢

You can use the predicate term_to_atom/2 to convert the atom (what you call a string) into an evaluable term, then use the is operator to perform the specified operation(s). 您可以使用谓词term_to_atom / 2将原子(称为字符串)转换为可评估的术语,然后使用is运算符执行指定的操作。 Care should be taken if security is a concern as this roughly equivalent to an eval in JavaScript. 如果要考虑安全性,则应格外小心,因为这大致相当于JavaScript中的eval

Full example 完整的例子

?- term_to_atom( T, '4 + 2 / 5' ).
T = 4+2/5.

?- term_to_atom( T, '4 + 2 / 5' ), X is T.
T = 4+2/5,
X = 4.4.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM