Zap
Zap

Reputation: 346

How do I specify to Prolog that all the elements of a list have to be 1 or 0?

How do I make sure that all the elements of a prolog list are either 0 or 1?

I need to generate a list of given length and make sure it has only these 2 numbers in it:
E.g. [0,0,0,0,0,0], [1,0,0,1,0,1,1] etc

I suppose the use of libraries like IC or FD is needed but I can't quite figure out how to deal with this with the methods in each.

Upvotes: 3

Views: 239

Answers (3)

jschimpf
jschimpf

Reputation: 5034

Specifically, for ECLiPSe:

?- lib(ic).
Yes (0.14s cpu)

?- length(Xs, 5), Xs :: 0 .. 1.
Xs = [_415{[0, 1]}, _429{[0, 1]}, _443{[0, 1]}, _457{[0, 1]}, _471{[0, 1]}]
Yes (0.00s cpu)

Any attempt to instantiate the lists elements to something other than 0 or 1 will then lead to failure.

Upvotes: 2

CapelliC
CapelliC

Reputation: 60034

Quite easy in basic Prolog, assuming it's fine to have an empty list:

allowed(0).
allowed(1).
zero_one(L) :- maplist(allowed,L).

?- length(L,10), zero_one(L).

that is, maplist/2 requires its first argument - a predicate - to be true for each list' element.

Without maplist, restricting to only 0 or 1:

zero_one([]).
zero_one([0|T]) :- zero_one(T).
zero_one([1|T]) :- zero_one(T).

Another alternative, with library(yall) and maplist/2:

zero_one(L) :- maplist([X]>>(X=0;X=1), L).

Upvotes: 1

joel76
joel76

Reputation: 5645

Suppose A is a list. Just says that A ins 0..1 example

 ?- [library(clpfd)].
 true.

 ?- length(A, 10),A ins 0..1.
 A = [_3820,_3826,_3832,_3838,_3844,_3850,_3856,_3862,_3868,_3874],
 _3820 in 0..1,
 _3826 in 0..1,
 _3832 in 0..1,
 _3838 in 0..1,
 _3844 in 0..1,
 _3850 in 0..1,
 _3856 in 0..1,
 _3862 in 0..1,
 _3868 in 0..1,
 _3874 in 0..1.

Upvotes: 5

Related Questions