Re: some quick help with lists

From: Tom Schrijvers (
Date: 11/23/04

Date: Tue, 23 Nov 2004 11:27:54 +0100

dirty_bit wrote:

> What I thought would be a simple first program to write in Prolog has
> some how become a problem. I am attempting to write a rule that takes
> a list and an integer. The integer is the sum of two elements in the
> list. (e.g. sum(list, num) ).
> I was trying to do something along the lines of:
> sum([H|T], A) :- select([H|T],X1,T2), select(T2,X2,_), A is +(X1,X2).
> This works just fine, but I would like for it to also be able to go
> the other way too. For example if I gave it sum(X, 3). X would equal:
> [1,2], [2,1], [1,2,3], etc. And it would need to stop at a certain
> list length that I could specify so it doesn't loop forever.
> Any suggestions would be greatly appreciated. Perhaps my code needs to
> be completely rewritten?

Arithmetic only works one way in plain Prolog: it is a one way constraint.
Only the A is allowed to be an unknown value. X1 and X2 have to be known.
Constraint Logic Programming extends Prolog with full arithmetic

Here is some code that imports the simple integer arithmetic constraint
solver included in SWI-Prolog.

:- use_module(library('clp/bounds')).

% generate a list of variables bounded by some maximal length
variable_list([X|Xs],N) :-
        N > 0,
        M is N - 1,

% compute sum of elements in list
sum([],S) :-
        S #= 0.
sum([X|Xs],S) :-
        S #= X + S0,

Now you can run your in different modi:

% straightforward:
?- sum([1,2],S).
S = 3 ;


% backwards:
?- variable_list(L,3), L in 1..10, sum(L,S), S #= 3, label([S|L]).

L = [3] ;

L = [1, 2] ;

L = [2, 1] ;

L = [1, 1, 1] ;


L in 1..10 constraints the variables in the list to be between 1 and 10,
otherwise there's an infinite number of possibilities. Labelling of the
variabels is necessary to instantiate the variables in the list to an
actual solution.

You can add additional constraints to the variabels in the list or drop the
S #= 3 constraint to run in a different modus.

Check the documentation of SWI-Prolog for more possibilities or look at the
constraints solvers included in your favorite Prolog system.