In writing accustomed to c,java this ordinary programming language, the first knowledge of Prolog really some adaptation, it just need you to tell the computer what to do, instead of telling the computer how to do it.
The subject is this:
For this question we consider binary expression-trees whose leaves is either of the form tree (empty, Num, empty) where Nu M is a number, or tree (empty, z, empty) in which case we'll think of the letter Z as a kind of "variable". Every tree is either a leaf or of the form tree (L, Op, R) where L and R were the left and right subtrees, and Op is one of The arithmetic operators ' + ', '-', ' * ', '/' (signifying addition, subtraction, multiplication and division).
Write a predicate tree_eval (Value, tree, eval) that binds eval to the result of evaluating the expression-tree tree, with The variable z set equal to the specified Value. For example:
?-Tree_eval (2, Tree (empty,z,empty),
' + ', tree (tree (empty,1,empty),
'/', Tree (empty,z,empty)), eval).
Eval = 2.5;
False.
? -Tree_eval (5, tree (empty,z,empty),
' + ', tree (tree (empty,1,empty),
'/', Tree (empty,z,empty)), eval).
Eval = 5.2;
False.
There are three kinds of situations in this question.
List some specifics first
Tree_eval (num, tree (empty,x,empty), eval):-X=z, Eval is Num.
Tree_eval (Num, Tree (empty,x,empty), eval):-Number (X), Eval is X.
These can be seen as the end condition of recursion.
The third case:
%case 3, left or right is a tree calcuate the node ' s children first.
Tree_eval (Num, Tree (left,x,right), eval):-
Tree_eval (Num, left, Lefteval),
Tree_eval (Num, right, Righteval),
X = '-',
Eval is lefteval-righteval.
Other operators, etc.