/* Sudoku using maplist/2 in Picat. Inspired by the Prolog model htps://rosettacode.org/wiki/Sudoku#Prolog The same example is here: - http://swish.swi-prolog.org/example/clpfd_sudoku.pl - https://www.swi-prolog.org/pldoc/man?section=clpfd-sudoku From https://www.swi-prolog.org/pldoc/man?section=clpfd-sudoku """ In this concrete case, the constraint solver is strong enough to find the unique solution without any search. """ It's true for this Picat model as well when using all_distinct/1, though I added solve/1 since I want it slightly more general. This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import util. import cp. main => go. go ?=> problem(1,Rows), sudoku(Rows), foreach(Row in Rows) println(Row) end, fail, % ensure unique solution nl. go => true. sudoku(Rows) => Rows :: 1..9, maplist(all_distinct, Rows), % don't need solve/1 % maplist(all_different, Rows), % all_different/1 need solve/1 maplist(all_distinct, Rows.transpose()), Rows = [A,B,C,D,E,F,G,H,I], blocks(A,B,C), blocks(D,E,F), blocks(G,H,I), solve(Rows). blocks([], [], []) => true. blocks([A,B,C|Bs1], [D,E,F|Bs2], [G,H,I|Bs3]) => all_distinct([A,B,C,D,E,F,G,H,I]), blocks(Bs1, Bs2, Bs3). problem(1, Rows) => Rows = [[_,_,_,_,_,_,_,_,_], [_,_,_,_,_,3,_,8,5], [_,_,1,_,2,_,_,_,_], [_,_,_,5,_,7,_,_,_], [_,_,4,_,_,_,1,_,_], [_,9,_,_,_,_,_,_,_], [5,_,_,_,_,_,_,7,3], [_,_,2,_,1,_,_,_,_], [_,_,_,_,4,_,_,_,9]]. maplist(Goal, List) => maplist_(List, Goal). maplist_([], _) ?=> true. maplist_([Elem|Tail], Goal) => call(Goal, Elem), maplist_(Tail, Goal).