Reputation: 125
I have a program in SICStus Prolog that runs the following constraints:
processList([Elem1,Elem2|_], X) :-
(Elem1 #= 0 #/\ Elem2 #= X) #\/
Elem1 #= X.
But I need to have it set up dynamically
processList([Elem1,Elem2,Elem3|_], X) :-
(Elem1 #= 0 #/\ Elem2 #= 0 #/\ Elem3 #= X) #\/
(Elem1 #= 0 #/\ Elem2 #= X) #\/
Elem1 #= X.
And if I call it with 4 elements I will have a bigger restriction, but the pattern is always the same.
I have already looked into the table predicate (tuples_in/2
, in SWI-Prolog), but that creates the need of me having to calculate all the possible valid combinations of values.
Is there any other way I can do this?
Upvotes: 2
Views: 343
Reputation: 18726
Using built-in predicate append/3
and Prolog library predicate maplist/2
we write:
:- use_module(library(lists)), [maplist/2]). processList(Zs, X) :- append(Prefix, [X|_], Zs), % `Zs` comprises `Prefix`, followed by `X` maplist(=(0), Prefix). % all items in `Prefix` are equal to 0
See it in action with SICStus Prolog 4.3.2!
| ?- processList(Zs, X).
Zs = [X|_A] ? ;
Zs = [0,X|_A] ? ;
Zs = [0,0,X|_A] ? ;
Zs = [0,0,0,X|_A] ? ;
Zs = [0,0,0,0,X|_A] ? ;
...
Upvotes: 2