<div class="notebook">
<div class="nb-cell markdown" name="md1">
# Example of `notebook` page style
This is a **notebook version** of the example page: contains
**runnable examples**.
- For supporting several Prologs probably a different
version of the notebook for each Prolog is needed.
- For example this one would be the Ciao/ALD version (serverless)
and this the SWISH version (server-based).
## An example:
Consider the factorial example, using Peano arithmetic, that we saw in the first part of the course:
~~~{.pl}
factorial(0,s(0)).
factorial(s(N),F) :-
factorial(N,F1),
times(s(N),F1,F).
~~~
This version is very attractive:
- It is fully reversible!
- But also inefficient...
However, we can also code it using ISO-Prolog arithmetic, i.e., `is/2`:
```prolog
... Z is X * Y ...
```
Note that this type of arithmetic has limitations: it only works in
one direction, i.e., `X` and `Y` must be bound to
arithmetic terms.
But it provides a (large!) performance gain. Also, meta-logical tests
(see later) allow using it in more modes.
The factorial program can be encoded using `is/2` as follows:
</div>
<div class="nb-cell program" name="p1">
factorial(0,1).
factorial(N,F) :-
N > 0,
N1 is N-1,
factorial(N1,F1),
F is F1*N.
</div>
<div class="nb-cell markdown" name="md2">
Try it:
</div>
<div class="nb-cell query" name="q1">
factorial(20,F).
</div>
<div class="nb-cell markdown" name="md3">
Now it works even for very large numbers:
</div>
<div class="nb-cell query" name="q2">
factorial(100,F).
</div>
<div class="nb-cell markdown" name="md4">
Note that wrong goal order can raise an error (e.g., moving the last
call to `is/2` before the call to factorial). We can solve this using constraints:
</div>
<div class="nb-cell program" name="p2">
:- use_module(library(clpq)).
factorialc(0,1).
factorialc(N,F) :-
{
N > 0,
N1 = N-1
},
factorialc(N1,F1),
{
F = F1*N
}.
</div>
<div class="nb-cell markdown" name="md5">
And now it runs in both directions, and more efficiently than Peano:
</div>
<div class="nb-cell query" name="q3">
factorialc(8,F).
</div>
<div class="nb-cell query" name="q4">
factorialc(N,40320).
</div>
</div>