Learning Prolog: Lab Session #6 - More Looping


Before I get into today's post, I wanted to include a picture of some firework that I managed to photograph a few days ago on my phone. A heard them outside and when I took a look out of the window, this is what I saw!
Anyway, Today's Prolog lab session was about more loops. These loops are different to the failure driven loops that we did last time though in that they are recursive instead. Here's an example:
loopa :-
write('Enter \'end.\' to exit.'), nl,
read(Input), (Input = end ; loopa).
The above is a simple rule that keeps asking for user input until the user enters 'end'.
?- loopa.
Enter 'end.' to exit.
|: hello.
Enter 'end.' to exit.
|: cheese.
Enter 'end.' to exit.
|: end.
true.
This is done through the semi colon, which acts as an or
operator. Although this works, it isn't very readable. Let's try something else.
% Stopping condition
loopb(end).
% Main loop
loopb(Input) :-
write('Enter \'end.\' to exit.'),
read(Input2),
loopb(Input2).
% Starter rule
go :-
loopb(something).
Much better. The above is divided up into the stopping condition (i.e. when the user types end
), the main loop, and a rule that kicks the rest of the program off. When go
is called, we call loopb
with something
as a parameter immediately. Since this doesn't match the fact loob(end)
, Prolog looks at the rule we defined, loopb(Input)
. Then it asks the user for input, and starts the process over again until the user inputs end
.
Here's an example of the above in action:
?- go.
Enter 'end.' to exit.gdsfgdrt.
Enter 'end.' to exit.sdfgsdgf.
Enter 'end.' to exit.sdfgsdfgertr.
Enter 'end.' to exit.cheese.
Enter 'end.' to exit.end.
true.
Having learnt this, one of the challenges was to write a rule in Prolog. A factorial is where you multiply an integer by all the integers greater than 0 but less than the integer. For example, 4!
(4 factorial) is 4x3x2x1
, which is 24). Here's what I came up with:
factorial(1, 1).
factorial(N, Factorial) :-
N2 is N - 1,
factorial(N2, Ans),
Factorial is N * Ans.
And here's an example of the above in action:
?- factorial(6, Answer).
Answer = 720 .
That concludes this post on the 6th Prolog lab session. If you don't understand something (or I've made a mistake!) please post a comment below and I'll do my best to help you. Also, if you have any, post your firework pictures below. I'd be interested to see them!