<div class="notebook">
<div class="nb-cell markdown">
### Moded versions
To translate the functionality of an imperative or functional language to Prolog, it suffices to use arithmetic predicates like `(is)/2` and `(=:=)/2`, which are *moded* and cannot be used in all directions. This does not take full advantage of the relational nature of Prolog.
For example, without libraries:
</div>
<div class="nb-cell program">
even_sum([], 0).
even_sum([H|T], Sum) :-
H mod 2 =:= 0, !,
even_sum(T, Sum0),
Sum is Sum0+H.
even_sum([_|T], Sum) :-
even_sum(T, Sum).
</div>
<div class="nb-cell query">
numlist(1, 10, L), even_sum(L, Sum).
</div>
<div class="nb-cell markdown">
Note though that this cannot be used in more general cases:
</div>
<div class="nb-cell query">
even_sum([_], Sum).
</div>
<div class="nb-cell markdown">
And now with (auto-loaded) libraries
</div>
<div class="nb-cell program">
even_sum(List, Sum) :-
include(even, List, EvenNumbers),
sum_list(EvenNumbers, Sum).
even(X) :- X mod 2 =:= 0.
</div>
<div class="nb-cell query">
numlist(1, 10, L), even_sum(L, Sum).
</div>
<div class="nb-cell markdown">
It still cannot be used in more general cases:
</div>
<div class="nb-cell query">
even_sum([_], Sum).
</div>
<div class="nb-cell markdown">
### Using the relational power of Prolog
And now what about using the actual power of Prolog for a version that can be used in all directions?
Using CLP(FD) constraints, you obtain declarative integer arithmetic that can be used as true relations over integers:
</div>
<div class="nb-cell program">
:- use_module(library(clpfd)).
list_even_sum([], 0).
list_even_sum([L|Ls], Sum) :-
E #<==> L mod 2 #= 0,
(E #/\ Sum #= Sum0 + L) #\/ (#\E #/\ Sum #= Sum0),
list_even_sum(Ls, Sum0).
</div>
<div class="nb-cell markdown">
Example:
</div>
<div class="nb-cell query">
list_even_sum([1,2,3,4], Sum).
</div>
<div class="nb-cell markdown">
And this version also works in more general cases:
</div>
<div class="nb-cell query">
list_even_sum([L|Ls], Sum).
</div>
<div class="nb-cell markdown">
As expected, we can use the _same code_ to constrain a variable to _even_ or _odd_ integers, if we in addition exclude 0:
</div>
<div class="nb-cell query">
list_even_sum([X], 0), X #\= 0.
</div>
<div class="nb-cell markdown">
There are powerful [meta-predicates](http://stackoverflow.com/questions/13664870/reification-of-term-equality-inequality) that let you considerably shorten the code above. See also [tinclude/3](http://stackoverflow.com/questions/13490900/delete-vowels-in-a-list/29963476#29963476).
This relational nature of the code is not available in other languages. It is what makes Prolog solutions often shorter and more powerful.
</div>
</div>