将[[Maybe Int]]转换为IO()

时间:2014-02-13 09:21:06

标签: haskell

在经历了“了解你一个Haskell”的几章后,我想亲自动手并决定实现一个数独求解器。我正在尝试从这里实现B1函数:http://www.cse.chalmers.se/edu/year/2013/course/TDA555/lab3.html < / p>

我的代码:

data Sudoku = Sudoku { getSudoku :: [[Maybe Int]] } deriving (Show, Eq)

rows :: Sudoku -> [[Maybe Int]]
rows (Sudoku rs) = rs

example :: Sudoku
example = Sudoku
    [ [Just 3, Just 6, Nothing,Nothing,Just 7, Just 1, Just 2, Nothing,Nothing]
    , [Nothing,Just 5, Nothing,Nothing,Nothing,Nothing,Just 1, Just 8, Nothing]
    , [Nothing,Nothing,Just 9, Just 2, Nothing,Just 4, Just 7, Nothing,Nothing]
    , [Nothing,Nothing,Nothing,Nothing,Just 1, Just 3, Nothing,Just 2, Just 8]
    , [Just 4, Nothing,Nothing,Just 5, Nothing,Just 2, Nothing,Nothing,Just 9]
    , [Just 2, Just 7, Nothing,Just 4, Just 6, Nothing,Nothing,Nothing,Nothing]
    , [Nothing,Nothing,Just 5, Just 3, Nothing,Just 8, Just 9, Nothing,Nothing]
    , [Nothing,Just 8, Just 3, Nothing,Nothing,Nothing,Nothing,Just 6, Nothing]
    , [Nothing,Nothing,Just 7, Just 6, Just 9, Nothing,Nothing,Just 4, Just 3]
    ]

printSudoku :: Sudoku -> IO ()
printSudoku s = do
    print . map (map (\x -> if isNothing x then 0 else fromJust x)) $ rows s

我试图将其打印为

Sudoku> printSudoku example
36..712..
.5....18.
..92.47..
....13.28
4..5.2..9
27.46....
..53.89..
.83....6.
..769..43

但我只能将其打印为

[[3,6,0,0,7,1,2,0,0],[0,5,0,0,0,0,1,8,0],[0,0,9,2,0,4,7,0,0],[0,0,0,0,1,3,0,2,8],[4,0,0,5,0,2,0,0,9],[2,7,0,4,6,0,0,0,0],[0,0,5,3,0,8,9,0,0],[0,8,3,0,0,0,0,6,0],[0,0,7,6,9,0,0,4,3]]

如果这是初学者问题的错误地方,我道歉。只是因为我已经尝试了一段时间并且陷入相对微不足道的事情并且令人沮丧。感谢

1 个答案:

答案 0 :(得分:8)

你很近!

关键是这个匿名函数:

(\x -> if isNothing x then 0 else fromJust x)

顺便说一句,这里有2个警告标志:使用isNothingfromJust

现在,由于此函数返回数字,因此您只能显示数字。但你想要的是角色。因此,只需将其重写为本地函数,如:

 showcell Nothing  = '.'
 showcell (Just n) = ....

===编辑:更一般的建议===

每当你发现自己写作时:

if isNothing x then a else f (fromJust x)

您应该使用显式本地函数或

替换它
maybe a f x

在你的情况下,你最初写的只是:

(\x -> maybe 0 id x)

减少到更好的

maybe 0 id

现在您只需将其更改为:

maybe '.' (head . show)

或其他什么。