在寫慣了 C,java這種普通的程式語言後,初識prolog真的有些適應不過來,它只需要你告訴電腦應該幹什麼,而不用告訴電腦怎麼做。
碰到的題目是這樣的:
For this question we consider binary expression-trees whose leaves are either of the form tree(empty, Num, empty) where Num is a number, or tree(empty, z, empty) in which case we will 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 are 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(tree(empty,z,empty), '+',tree(tree(empty,1,empty), '/',tree(empty,z,empty))), Eval).Eval = 2.5 ;false.?- tree_eval(5, tree(tree(empty,z,empty), '+',tree(tree(empty,1,empty), '/',tree(empty,z,empty))), Eval).Eval = 5.2 ;false.
這題一共有三種情況
先列出一些具體情況
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.
這些可以看成遞迴的結束條件
第三種情況:
%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.
其他動作符以此類推