gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:22:20 25 4
gpt4 key购买 nike

在读完“Learn You A Haskell”的几章后,我想写一些实际的东西,并决定实现一个数独求解器。我试图从这里实现 B1 函数:http://www.cse.chalmers.se/edu/year/2013/course/TDA555/lab3.html

我的代码:

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]]

如果这是此类初学者问题的错误地方,我深表歉意。只是我已经尝试了一段时间并陷入了一些相对琐碎的事情并且变得令人沮丧。谢谢

最佳答案

你已经很接近了!

关键点是这个匿名函数:

(\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)

或者其他什么。

关于haskell - 将 [[Maybe Int]] 转换为 IO (),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21749841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com