prolog中的树操作

在写惯了 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.

 

其他操作符以此类推

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值