Lesson goal: Seeing how Prolog counts

Previous: Introduction Part II: Compound facts | Home | Next: Adding two fractions

As an analogy with this lesson on counting, here's the way we'd get Prolog counting. First, (reading bottom to top), we'll define a goal of range(1,10) to start Prolog counting from 1 to 10.

The range(S,E) clause is the main counting clause. It is passed two numbers, $S$ and $E$, standing for "start" and "end." These serve as the range to count between.

Range calls another clause count like this count(S,E,S), which is the clause that actually does the counting. There are two rules for count, so let's look at both (the 2nd one first).

The 2nd clause for count looks like this: count(S,E,N) :- ... It takes in a start S and end E as the counting bounds. It also needs a variable N to serve as the counting variable (kind of like the variable used in a for-loop). You can see in the range clause that count(S,E,S) starts N at S, which is where we want the count to start. This count clause will succeed based on a few steps of logic: First, $S\le N\le E$. Second, let's display $N$ to the screen using write (which always succeeds). Third, let's find $N_1$ which is the current count $N$, but advanced by 1. Lastly, count is invoked again, but at $N_1$ now.

The 1st clause count(_,E,N) :- N > E. This looks for N becoming greater than E, which is the case where we want to stop counting. The _ is the anonymous variable in Prolog, which is where S should go. But since S isn't needed, as we're only looking at E and N, we put in the _ as shown.

Prolog works now with the two count clauses, trying to satisfy them. The 1st clause will fail as we get started counting, since $N\le E$, so Prolog will look to the 2nd clause, which succeeds as long as $S\le N\le E$. The call to count(S,E,N1) at the end of the 2nd clause is what keeps the counting going. Prolog always looks at clauses in the order they appear in the code, so it'll go (re)examine the first clause. If $N>E$ succeeds, then Prolog will hit the period, satisfying count(S,E,S) with no further calls to count requested. The counting will now stop. If $N\le E$, then the 2nd clause will succeed (after the first was seen to fail), and on goes the count.

Now you try. Try changing the range to count between any two numbers you wish.

Type your code here:


See your results here: