我正在努力从http://www.cse.chalmers.se/edu/year/2013/course/TDA555/lab3.html开始制作数独求解器的分步练习。在这里,我试图表达Sudok的行,列和框约束
data Sudoku = Sudoku { getSudoku :: [[Maybe Int]] } deriving (Show, Eq)
rows :: Sudoku -> [[Maybe Int]]
rows (Sudoku rs) = rs
columns :: Sudoku -> [[Maybe Int]]
columns = transpose . rows
boxes :: Sudoku -> [[Maybe Int]]
boxes s = a ++ b ++ c
where a = map (concat . take 3) s1
b = map (concat . take 3 . drop 3) s1
c = map (concat . drop 6) s1
s1 = transpose . map (\xs -> [take 3 xs,take 3 (drop 3 xs), drop 6 xs]) $ rows s
我设法让它工作但是我想重构在s1上应用的3个函数以将a,b,c放入列表中。我试过< *>但不知何故无法让它发挥作用。感谢
答案 0 :(得分:3)
如果你 想要
,你可以使用Applicative
来编写它
boxes2 s = concat $ [a,b,c] <*> [s1]
这与
相同concatMap ($s1) [a,b,c]
或者,你可以这样做:
boxes3 :: Sudoku -> [[Maybe Int]]
boxes3 = map concat . concat . map (f . transpose) . f . getSudoku
where f = unfoldr (\x -> if null x then Nothing else Just $ splitAt 3 x)