I'm new to Haskell, and I've come across the following code that baffles me:
foldr (zipWith (:)) (repeat []) [[1,2,3],[4,5,6],[7,8,9,10]]
It produces the following result, which after playing around with it, I'm not entirely sure why:
[[1,4,7],[2,5,8],[3,6,9]]
I'm under the impression that (:) prepends items to a list, and that (repeat []) produces an endless amount of empty lists [], and that foldr takes a function, an item, and a list, and condenses the list by consecutively applying the function to each item in the list along with the results.
That is to say, I intuitively understand how the following code produces a result of 10:
foldr (+) 1 [2,3,4]
But, I'm not at all sure why foldr (zipWith (:)) (repeat []) takes a list of lists and produces another list of lists with items grouped by their original inner indices.
Any explanation would be enlightening.
This is very simple.
foldris defined so thatthus,
Or, here,
And that's that.
(Next on the menu,
traverse ZipList [[1,2,3],[4,5,6],[7,8,9,10]]... :) or maybe later.)As for the other example, it is
because
+is strict in both of its arguments.zipWithis not strict in both arguments, nor is the(:), so the first sequence should be taken as an illustration only. The actual forcing will occur in the top-down order, not bottom-up. For instance,fully in accordance with