[Haskell-cafe] Rotating matrices

David House dmhouse at gmail.com
Fri Jun 16 03:07:08 EDT 2006


On 15/06/06, Stefan Holdermans <stefan at cs.uu.nl> wrote:
>    transpose = foldr (zipWith (:)) (repeat [])

While one-liners like this are very pretty, it's worth thinking about
how they work:

1. (:) takes an element and a list and prepends that element to the list.
2. zipWith (:) takes a list of elements and a list of lists and
prepends each element to its corresponding list.
3. repeat [] is the infinite list [[], [], [], [], ... ], i.e. the
infinite list of empty lists.
4. transpose, therfore, takes the last list in your list-of-lists
input, then prepends each element of it to the empty list. That is, if
the last list in the input was [x1, x2, ..., xn] then it produces
[[x1], [x2], ..., [xn]].
5. Then this is repeated with the penultimate list in the input (say
its elements are y1..yn), giving [[y1, x1], [y2, x2], ..., [yn, xn]]
6. And so on down the input list.

-- 
-David House, dmhouse at gmail.com


More information about the Haskell-Cafe mailing list