listprologconditional-statementselementeclipse-clp

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.


Solution

  • 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.