How can I tell Prolog that all elements of a list must be 1 or 0?

How can I make sure that all elements of the prologue list are 0 or 1?

I need to create a list of a given length and make sure there are only these 2 numbers in it:
For example. [0,0,0,0,0,0], [1,0,0,1,0,1,1] etc.

I suppose using libraries like IC or FD , but I can't figure out how to deal with this with methods in each.

+3


source to share


3 answers


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 list items for anything other than 0 or 1 will result in an error.

+2


source


Suppose A is a list. Just says 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.

      

+5


source


Simple enough in basic Prolog, assuming it has an empty list:

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

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

      

those. maplist / 2 requires its first argument, a predicate, to be true for every element in the list.

Without a list limiting only 0 or 1:

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

      

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

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

      

+1


source







All Articles