Tree operations in the Prolog

Source: Internet
Author: User
Tags arithmetic operators eval

Accustomed to c,java this common programming language, the first to understand the Prolog really some adaptation, it only needs you to tell the computer what to do, without telling the computer how to do.

The problems encountered are as follows:

For this question we consider binary expression-trees whose leaves are the "form tree" (either, Num, empty) where empty M is a number, or tree (empty, z, empty) in which case we'll have the letter Z as a kind of "variable". Every 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 The arithmetic operators ' + ', '-', ' * ', '/' (signifying addition, subtraction, multiplication and division).

Write a predicate tree_eval (Value, tree, eval) which binds eval to the "result of evaluating" expression-tree tree, with The variable z set equal to the specified Value. For example:

?-Tree_eval (2, Empty,z,empty,
                 ' + ', tree (empty,1,empty),
                      '/', Tree (empty,z,empty)), Eval.
Eval = 2.5;
False.

? -Tree_eval (5, tree (empty,z,empty),
                 ' + ', tree (empty,1,empty),
                      '/', Tree (empty,z,empty)), Eval.
Eval = 5.2;
False.

There are three kinds of situations in this question.

Let's list some specific situations
  
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 conditions of recursion.

In the third case:

%case 3, left or right are a tree calcuate the node ' s children.
Tree_eval (Num, Tree (left,x,right), eval):-
Tree_eval (Num, left, Lefteval),
Tree_eval (Num, right, Righteval),
X = '-',
The 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.