prolog中的樹操作

來源:互聯網
上載者:User

在寫慣了 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.

 

其他動作符以此類推

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.