Prolog solution to the prefix arithmetic expression with an unknown variable

I want to make an arithmetic solver in Prolog, which can have operations +, -, *, ^ by numbers> = 2. It should also be possible to have the variable x. The entry must be a prefix in the list.

I created a program that parses an arithmetic expression in prefix format in the syntax tree. So that:

?- parse([+,+,2,9,*,3,x],Tree). Tree = plus(plus(num(2), num(9)), mul(num(3), var(x))) . 

(1) At this stage, I want to expand this program to be able to solve it for a given value of x. This must be done by adding another predicate (Tree, Value, Solution) , which gave a value for unknown x, calculates the solution.

Example:

 ?- parse([*, 2, ^, x, 3],Tree), evaluate(Ast, 2, Solution). Tree = mul(num(2), pow(var(x), num(3))) , Solution = 16. 

I'm not sure how to solve this problem due to lack of Prolog skills, but I need a way to set var (x) to num (2), as in this example (because x = 2). Maybe a member in Prolog can be used for this. Then I have to solve it using maybe is / 2

Change My attempt to solve it. Getting error: <Undefined procedure: rating / 3 However, there are definitions for: rating / 5 '

 evaluate(plus(A,B),Value,Sol) --> evaluate(A,AV,Sol), evaluate(B,BV,Sol), Value is AV+BV. evaluate(mul(A,B),Value,Sol) --> evaluate(A,AV,Sol), evaluate(B,BV,Sol), Value is AV*BV. evaluate(pow(A,B),Value,Sol) --> evaluate(A,AV,Sol), evaluate(B,BV,Sol), Value is AV^BV. evaluate(num(Num),Value,Sol) --> number(Num). evaluate(var(x),Value,Sol) --> number(Value). 

(2) I would also like to express this in postfix form. Having the predicate postfixform (Tree, Postfixlist)

Example:

 ?- parse([+, *, 2, x, ^, x, 5 ],Tree), postfix(Tree,Postfix). Tree = plus(mul(num(2), var(x)), pow(var(x), num(5))) , Postfix = [2, x, *, x, 5, ^, +]. 

Any help with (1) and (2) would be greatly appreciated!

0
source share
1 answer

You do not need to use grammar for this, as you do it. You should use the usual rules.

This is the template you need to execute.

 evaluate(plus(A,B),Value,Sol) :- evaluate(A, Value, A2), evaluate(B, Value, B2), Sol is A2+B2. 

and

 evaluate(num(X),_Value,Sol) :- Sol = X. evaluate(var(x),Value,Sol) :- Sol = Value. 
+1
source

Source: https://habr.com/ru/post/957436/


All Articles