在写惯了 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.
其他操作符以此类推
本文介绍如何使用Prolog语言编写程序来评估含有变量z的二叉表达式树,并给出具体的实现细节与示例。

9554

被折叠的 条评论
为什么被折叠?



