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.
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). Care should be taken if security is a concern as this roughly equivalent to an eval
in JavaScript.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.