7. Arithmetic
Chapter 5 showed that 1 + 2 is only a term. To compute it, you ask for it with is/2.
is
X is Expression computes the expression and unifies the result with X.
/always gives a float, such as3.5or2.0.//divides integers and drops the fraction.modgives the remainder.^raises a number to a power. Integers have no size limit, soX is 2 ^ 100gives the exact integer.**does the same, but always gives a float.
The right side must be known
is/2 computes the right side right away. All of its variables must already have values.
The second query gives an error, instantiation_error. When Prolog reaches is, X has no value yet, so there is nothing to compute. Unlike the relations in earlier chapters, arithmetic works only in one direction.
Comparing numbers
| Goal | True when |
|---|---|
X =:= Y |
the values are equal |
X =\= Y |
the values are different |
X < Y |
X is less than Y |
X > Y |
X is greater than Y |
X =< Y |
X is less than or equal to Y |
X >= Y |
X is greater than or equal to Y |
Both sides are computed, so they can be expressions. Note that "less than or equal" is =<, not <=.
1 + 2 =:= 3 is true, because it compares values. 1 + 2 = 3 is false, because it compares terms.
Counting with recursion
Now you can write the length of a list.
len([], 0).
len([_ | T], N) :- len(T, N0), N is N0 + 1.The empty list has length 0. Any other list is one longer than its tail. Note the order in the second clause. len(T, N0) must come first, so that N0 has a value when is needs it.
Accumulators
len/2 above first walks to the end of the list, then adds 1 on the way back. Another way is to carry the count so far in an extra argument, called an accumulator.
len/2 and len/3 are different predicates, because the numbers of arguments are different. len/3 counts as it goes down the list. When the list is empty, the count so far is the answer. This is like a for loop with a counter variable.
Numbers in a range
between(Low, High, X) gives each integer from Low to High, one per answer.
In the second query, the first answer is the first number whose square is greater than 20. between/3 makes the candidates, and the comparison tests them. Chapter 8 builds on this idea.
Try it
- The box below has
max_list/2. Writemin_list/2in the same way, with theminfunction. - Write
range(Low, High, List), which gives[Low, ..., High]. For examplerange(1, 4, L)givesL = [1, 2, 3, 4]. - Ask
?- X is 2 ^ 100.and?- X is 2 ** 100.and compare the results.