Swiftle
Swiftle

Reputation: 11

Prolog: recursive list construction

I'm having problem constructing a list of lists in my prolog program. I have a predicate which gives me back a single case of a row. I have to group all the cases of this row and transform them into a list of lists. I can access them just fine but when I exit, all I'll get is the first element.

Here's the code:

sudoku3to2 :- s3to2(1).
s3to2(Line) :- 
   Line < 9, 
   Line1 is Line+1,
   s3getLine(Line,0,[L]),   
   assert(sudoku2(Y,L])),
   s3to2(Line1).
s3to2(9).

s3getLine(Line,X,  , ) :- 
   X < 9, 
   X1 is X + 1, 
   sudoku3(Line,X, ),
   s3getLine(Line,X1, , ).
s3getLine(Line,9,L,L).

sudoku3/3 will return the element at the X,Y coordinate. When I get to s3getLine(Line,9,L,L) I'll start going back. I want to keep all the elements I've gathered and not just the first one. And I'm really having trouble constructing the proper predicate calls.

Upvotes: 1

Views: 585

Answers (1)

CapelliC
CapelliC

Reputation: 60004

findall/3 is the 'list constructor' more easily understood.

It's a builtin that list all solutions found, shaping the elements with a specified pattern. Here the pattern is really just the variable we are interested to.

I use between/3 to obtaing a correctly ordered matrix, without regard to sudoku3 rules order.

sudoku3(1, 1, a).
sudoku3(1, 2, b).

sudoku3(2, 1, c).
sudoku3(2, 2, d).

mat(M) :-
  W = 2,
  findall(Row,
    (between(1, W, R),
     findall(V, (between(1, W, C), sudoku3(R, C, V)), Row)
    ), M).

Result:

?- mat(M).
M = [[a, b], [c, d]].

You should change W=9.

HTH

Upvotes: 1

Related Questions