2

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?

repeat
  • 18,496
  • 4
  • 54
  • 166
CMJunior
  • 95
  • 1
  • 1
  • 6

1 Answers1

2

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] ? ;
...
Community
  • 1
  • 1
repeat
  • 18,496
  • 4
  • 54
  • 166
  • 1
    I think I was not clear enough. I was using constraint logic programming (using the clpr library to be exact), so I couldn't really state that the element is 0 (like maplist does), I need to make a restriction using the '#' operator. At the time I shown my professor that I couldn't create dynamic restrictions and not even him could resolve the problem (they add new problems every year to the course to avoid cheating). I ended up only needing to use the first piece of code. – CMJunior Sep 18 '15 at 13:14
  • @CMJunior. Please tell me more! I haven't been using clp(R) for quite a while, but intuitively I would have guessed that it is (in principle) interoperable with plain Prolog using syntactic unification. – repeat Sep 18 '15 at 13:25
  • 1
    We needed to make a prolog version of the Easy as ABC puzzle. One of the restrictions needed to be that, if there's a letter before a column or row, from watching the board from the column/row's perspective, you need to see that letter, in other words, all the board spaces until you see the letter from that perspective must be white (in our code, with value 0). For the lab assignment we also needed to make the board size dynamic, so the user would tell the program which board size he wanted to play on. That created a problem on the restrictions which generated this thread. – CMJunior Sep 19 '15 at 14:46