Date

Yesterday I implemented a predicate to compute the min and max of a list. Today I'm doing the same, but now with constraints.

The code looks pretty much the same thanks to the handy min and max constraints.

:- use_module(library(clpfd)).

min_and_max([V], A, B) :-
    V #= A, V #= B.
min_and_max([H|R], Min, Max) :-
    min_and_max(R, RMin, RMax),
    Min #= min(H, RMin),
    Max #= max(H, RMax).

% list_length_min_and_max(+Size, ?Min, ?Max, ?L)
list_length_min_and_max(Size, Min, Max, L):-
    length(L, Size),
    min_and_max(L, Min, Max).

And here's an example call:

?- list_length_min_and_max(5, 1, 42, L), sum(L, #=, 60), all_distinct(L), label(L).
L = [1, 2, 3, 12, 42] ;
L = [1, 2, 3, 42, 12] ;
L = [1, 2, 4, 11, 42] ;
L = [1, 2, 4, 42, 11] ;
L = [1, 2, 5, 10, 42] ;
L = [1, 2, 5, 42, 10] ;
L = [1, 2, 6, 9, 42] ;
...