2

I am parsing a text file that contains lines of numbers. I want to turn them into [[[Int]]]. (A list of cells inside of a list of rows inside of a list of boards.)

sudoku.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 yields [[String]] and I want to use sudokus to yield [[[Int]]]. That requires a deep mapping that looks awful:

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

Is there a more Haskellian way to write the sudokus function?


For reference:

> 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]]]
asked Mar 9, 2020 at 11:30

1 Answer 1

6

You can wrap a value in a list by making use of pure :: Applicative f => a -> f a, hence we can write the \char -> read [char], as read . pure.

Next we can write the \row -> map (read . pure) row lambda expression as map (read . pure). So that means that we can rewrite the line to:

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

or we can avoid these brackets with:

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

Here it thus means that the (read . pure) is the mapping function of the "innermost" map.

answered Mar 9, 2020 at 11:36
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.