gpt4 book ai didi

parsing - 在 Haskell 中编写深度映射的更好方法?

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

我正在解析一个包含数字行的文本文件。我想把它们变成[[[Int]]]。 (板列表内的行列表内的单元格列表。)

数独.txt

530070000
600195000
098000060
800060003
400803001
700020006
060000280
000419005
000080079

400700500
300800001
700900008
060030010
090070050
080010790
002006900
005000030
000004200
...

main.hs

parseTextExample :: IO ()
parseTextExample = do
handle <- openFile "sudoku.txt" ReadMode
contents <- hGetContents handle
let splitBoards = splitWhen (== "") $ lines contents
let sudokus = map (\board -> map (\row -> map (\char -> read [char] :: Int) row) board) splitBoards
print sudokus
hClose handle

splitBoards 产生 [[String]] 并且我想使用 sudokus 产生 [[[Int]]]。这需要一个看起来很糟糕的深度映射:

map (\board -> map (\row -> map (\char -> read [char]::Int) row) board) splitBoards

是否有更符合 haskell 风格的方法来编写 sudokus 函数?

<小时/>

供引用:

> print splitBoards
>[["530070000","600195000","098000060","800060003","400803001","700020006","060000280","000419005","000080079"],["400700500","300800001","700900008","060030010","090070050","080010790","002006900","005000030","000004200"]]
> print sudokus
>
[[[5,3,0,0,7,0,0,0,0],[6,0,0,1,9,5,0,0,0],[0,9,8,0,0,0,0,6,0],[8,0,0,0,6,0,0,0,3],[4,0,0,8,0,3,0,0,1],[7,0,0,0,2,0,0,0,6],[0,6,0,0,0,0,2,8,0],[0,0,0,4,1,9,0,0,5],[0,0,0,0,8,0,0,7,9]],[[4,0,0,7,0,0,5,0,0],[3,0,0,8,0,0,0,0,1],[7,0,0,9,0,0,0,0,8],[0,6,0,0,3,0,0,1,0],[0,9,0,0,7,0,0,5,0],[0,8,0,0,1,0,7,9,0],[0,0,2,0,0,6,9,0,0],[0,0,5,0,0,0,0,3,0],[0,0,0,0,0,4,2,0,0]]]

最佳答案

您可以使用 pure :: Applicative f => a -> f a 将值包装在列表中,因此我们可以将 \char -> read [char] 写为 read 。纯

接下来我们可以将 \row -> map (read .pure) row lambda 表达式编写为 map (read .pure)。这意味着我们可以将该行重写为:

let sudokus = map (map (map (read . pure))) splitBoards :: [[[Int]]]

或者我们可以通过以下方式避免这些括号:

let sudokus = (<b>map . map . map</b>) (read . pure) splitBoards :: [[[Int]]]

这里意味着(read .pure)是“最里面的”map的映射函数。

关于parsing - 在 Haskell 中编写深度映射的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60599682/

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