在 Haskell 中扩展数独解算器的功能

Expand function of a sudoku solver in Haskell

我很难理解 this 数独求解器的一部分。我不明白扩展功能是如何工作的。

expand                :: Matrix Choices -> [Matrix Choices]
expand m              =
   [rows1 ++ [row1 ++ [c] : row2] ++ rows2 | c <- cs]
   where
      (rows1,row:rows2) = break (any (not . single)) m
      (row1,cs:row2)    = break (not . single) row

这里发生了什么?一个简短的解释会很有帮助。

如果有人想知道,

type Matrix a = [a]
type Choices  = [Value]
type Value    = Char

这是

expand m = [rows ++ ... ++ rows 2 | c <- cs]

其中 ...

[ row1 ++ ([c] : row2) ]

各种局部变量定义在where块中。换句话说,我们正在搜索输入矩阵并将其分解为一对结果。

如果你的问题是"what does this all mean?",那么坦率地说,我不知道。此代码不是我所说的 "intuitive".

幸运的是,您 link 的代码得到了很好的注释。引用上面的函数:

The function expand behaves in the same way as collapse, except that it only collapses the first square with more than one choice:

直觉上,函数 expand 接受数独并找到第一个单元格,其中仍然有多个选择。然后,它会扩展该选择,生成许多数独,每个数独都有一个特定的选择。即转(大致):

[ some data ... , [ data, ... [1,2,3] ... data ] , other data ]

进入

[[ some data ... , [ data, ... [1] ... data ] , other data ]
,[ some data ... , [ data, ... [2] ... data ] , other data ]
,[ some data ... , [ data, ... [3] ... data ] , other data ]]

关键行是这些:

 (rows1,row:rows2) = break (any (not . single)) m

这里,row是第一行有一个非单选的单元格。 rows1,rows2 是数独中的 before/after 行。

 (row1,cs:row2)    = break (not . single) row

这里,csrow的第一个非单选单元格。 row1,row2row 中的 left/right 部分。