Tree operations in the Prolog

Source: Internet
Author: User
Tags arithmetic operators eval

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.