views:

650

answers:

1

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?

+3  A: 

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.

starblue