Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog operator precedence and rules matching

I have the next two facts loaded in my prolog interpreter:

foo(U+V,1).
foo(U*V,2).

Now I try the next queries with that results:

foo(x*x+x,R).  -->  R = 1
foo(x+x*x,R).  -->  R = 1
foo(x*x*x,R).  -->  R = 2

Now I try with the next query:

foo(x*x-x,R).  -->  no

As I understand, this is explained by how the operator precedence build the tree expression:

x+x*x  -->  +           so it matches with  -->  +
           / \                                  / \
          x   *                                U   V
             / \
            x   x

x-x*x  -->  -           DOES NOT matches any fact.
           / \                             
          x   *                                
             / \
            x   x

Is this explanation correct?

like image 306
Ricardo Avatar asked Apr 20 '09 10:04

Ricardo


1 Answers

Yes, this is correct.

The default operator precedence is defined to be natural, i.e. use the normal mathematical precedence. But if you don't like that you can redefine it.

Whether changing the precedence is a great idea is another matter, it effectively changes the syntax of Prolog and can lead to parsing problems. Especially if you change the precedence of the operators for the Prolog syntax, with precedence above 1000.

like image 97
starblue Avatar answered Oct 04 '22 05:10

starblue