Solving Sudoku

What is Sudoku?
 A simple but addictive puzzle, invented in the USA in 1979 and called Number Place;  Became popular in Japan in 1986, where it was renamed Sudoku (~ “single number”);  First appeared in UK newspapers in 2004, and became an international craze in 2005.
1

Example
Fill in the grid so that every row, column and box contains each of the numbers 1 to 9:
2 7 1 6 3 8 5

11
. which is improved in a series of steps.  Emphasis on pictures rather than code.This Talk
 We show how to develop a program that can solve any Sudoku puzzle in an instant.  Start with a simple but impractical program. plus some lessons about algorithm design.

Representing a Grid
type Grid
type Matrix a
=
=
Matrix Char
[Row a]
type Row a
=
[a]
A grid is essentially a list of lists. but matrices and rows will be useful later on.
12
.

Validity Checking
Let us say that a grid is valid if it has no duplicate entries in any row. column or box:
valid :: Grid  Bool valid g = all nodups (rows g)  all nodups (cols g)  all nodups (boxs g)
A direct implementation.
17
. without concern for efficiency.

but impractical!
21
.Does It Work?
The easy example has 51 blank squares. resulting in 951 grids to consider. which is a huge number:
4638397686588101979328150167890591454318967698009
> solve easy ERROR: out of memory
Simple.

22
.  Pruning such invalid choices before collapsing will considerably reduce the search space. an initial entry of 1 precludes another 1 in the same row.  For example. column or box.Reducing The Search Space
 Many choices that are considered will conflict with entries provided in the initial grid.

pruning leaves around 381 grids to consider.But…
For a gentle example. which is still a huge number:
443426488243037769948249630619149892803
> solve' gentle
No solution after two hours .we need to think further!
29
.

 Discarding these bad choices is the key to obtaining an efficient Sudoku solver.Reducing The Search Space
 After pruning there may still be many choices that can never lead to a solution.  But such bad choices will be duplicated many times during the collapsing process.
30
.

Blocked Matrices
Let us say that a matrix is blocked if some square has no choices left. column. or if some row.a blocked matrix can never lead to a solution.
31
. or box has a duplicated single choice:
1 3 4
1 2
1 3
Key idea .

 This program can now solve any newspaper Sudoku puzzle in an instant!
34
.Notes
 Using fix prune rather than prune makes the program run slower in this case. because they are guaranteed to be valid by construction.  No need to filter out valid grids.