Department of Computer Science



next up previous
Next: Structured Data: Lists Up: A goal directed programming Previous: Predicates and terms


Arithmetic


Subsections

The Evaluable Predicate is

Prolog includes some predicates that force the evaluation of structures as arithmetic expressions. The predicate is takes 2 arguments, the first a variable and the second a simple numeric value or a functor structure where the functor is an arithmetic operator. So:
      | ?- is(X, +(*(3,3), *(4,4))).
      X = 25 ;
      no 
      | ?-
Or since is is also defined as an infix predicate as are the functors + and *:
      | ?- X is 3*3 + 4*4.
      X = 25 ;
      no 
      | ?-

Numeric Relational Predicates

The relational operator predicates <, >, <= and >= also force the evaluation of an infix operator expression numerically, so:
      | ?- 7+1 < 7.
      no 
      | ?-

Numeric functions in Prolog

Predicates can be written to express the idea of numerical functions. Say the function $f$ of two arguments produces a simple result this must be represented as a prolog predicate of 3 arguments that expresses the relationship between pairs of arguments and their results. So for example the function sumsq for sum of squares takes 2 arguments and gives a simple result, this is represented by the following predicate:
      sumsq(1,1,2).  
      sumsq(1,2,5).
      sumsq(2,1,5).  
      sumsq(2,2,8).
      sumsq(2,3,13).
      ...
this is of course silly as the 3rd argument can be computed for any pair of arguments using an evaluable predicate:
      | ?- [user].  
      sumsq(X,Y,Z) :- Z is X*X + Y*Y.  
      ^d
      [eof] 
      | ?- sumsq(4,5,R).
      R = 41

      | ?-
Another example is the gcd predicate which computes the greatest common divisor of 2 integers. It is a relationship between the two numbers and their divisor. So if given a goal with the third argument a variable it finds the greatest common divisor:
      | ?- gcd(30,36,X).
      X = 6

      | ?-
The relationship is that (1) if the 2 numbers are the same then the greatest common divisor is the same, (2) otherwise repeatedly subtract the smaller from the larger until they are the same. The rules for gcd are as follows:
      gcd(X,X,X).
      gcd(X,Y,D) :- 
            X > Y, NEWX is X-Y, gcd(NEWX,Y,D).
      gcd(X,Y,D) :-
            X < Y, NEWY is Y-X, gcd(X,NEWY,D).


next up previous
Next: Structured Data: Lists Up: A goal directed programming Previous: Predicates and terms


Page generated: 2002-11-04 by Bob Dickerson

© University of Hertfordshire Higher Education Corporation (1998)

Disclaimer