This no doubt moronic question is inspired from What does this list permutations implementation in Haskell exactly do?
Suppose
perms [] = [[]]
perms xxs = [ (y:ys) | ( y, xs ) <- pix xxs , ys <- perms xs ]
--where
pix [] = []
pix ( x:xs ) = ( x , xs ) : [ ( y, x : ys ) | ( y, ys ) <- pix xs ]
Twan van Laarhoven writes "the first thing this function does is pick the first element from the entire list, which is not lazy at all." OK - sure ! But I am confused -
I do not understand why ghci does the following:
*Main> let p = perms [1..]
*Main> let hs = map head p
*Main> take 1 hs
*** Exception: stack overflow
Why can't ghci print [1]?
Sigh...
peter
Comment on Answers:
As I said in my replies to Carsten's answer, I had 'reasoned' that my
*Main> let hs = map head p
*Main> take 1 hs
along with Haskell's laziness, would allow ghci not to calculate the ys in (y:ys) in perms, since the above only 'wanted' the value of the first 'y'; in short I was arguing that I was not really calculating the first term of perms [1..] at all. But, as both Carsten and Reid Barton in effect point out below, laziness is besides the point, and my argument was wrong.
To add to (and, I hope, not mangle) their answers, if
ans = take 1 hs
then, because of the list comprehension in the definition of perms,
ans is in the image of some function from the Cartesian product
(pix [1..]) X perms [2..].
But how do I know that the Cartesian product, the domain of my function, is not the empty set? For, otherwise, ans does not exist... ( i.e., how do I know that the first term of perms[1..] exists? Or, as Reid Barton more succinctly put it, how do I know that perms [1..] is not empty?)
The product is not empty if and only each factor is not empty. I know that the first is not empty (inspection!) - but how do I know that the perms [2..] factor is not empty? Oh - alas, by recursion, I am dead.