While learning Haskell, I was looking for a concise implementation of a function which “reshapes” a list into a matrix.
Given the number of rows
r, the number of columns
c, and a list
the function should take
r*c values from the list
and create a
c matrix out of them.
Here’s the type:
First I wrote a simpler function that would split a list into chunks of a given size, like this:
Using the above, toMatrix could be implemented this way:
I had a feeling that a function like
chunksOf should be already present
somewhere in the standard library,
so I asked Hoogle, but to no avail.
but it operated on
(I retroactively named my function after the one in
However, Hoogle returned
replicateM as well…
… and I realized I could use it with the state monad to implement toMatrix. The state could contain the list of values yet to be consumed, and the action to be replicated could be chopping off c values from the list:
After a while I realized that the same function could be written in a much more concise form:
The solution was, therefore:
The second version is good enough for me
and as a bonus it helped me understand the state monad.
Note that the two implementations of toMatrix are not equivalent,
as they handle lists shorter than
r*c in different ways.
Future work: find a concise and preferably point-free implementation of
This answer on StackOverflow contains a very nice implementation of chunksOf.