Matching patterns and endless lists

I am having trouble understanding this simple piece of code:

-- This works:     foldr go1 [] [1..]
-- This doesn't:   foldr go2 [] [1..]

go1 a b = a : b

go2 a [] = a : []
go2 a b  = a : b

Folding with go1immediately begins to return values, but go2it seems to wait for the list to end.

Obviously, pattern matching results in something being handled differently. Can someone explain what exactly is going on here?

+4
source share
4 answers

In contrast go1, go2checks if its second argument is empty. To do this, evaluate the second argument, at least enough to determine if it is empty or not.

, foldr :

go1 go2 : 1 foldr go [] [2 ..]. go1 , foldr - 1 :: foldr go [] [2 ..], , .

go2 foldr go [] [2 ..] , . foldr go [] [3 ..] . .

+4

, , , , . , . interleave, .

interleave :: [a] -> [a] -> [a]
interleave  xs     []    = xs
interleave  []     ys    = ys
interleave (x:xs) (y:ys) = x : y : interleave xs ys

.

interleave  []    ys = ys
interleave (x:xs) ys = x : interleave ys xs

: http://en.wikibooks.org/wiki/Haskell/Laziness

+2

- .... - , go1 go2, , b==[], ,

go1 a, b.

go1 a b -> create and return the value of a, then calculate b 

go2 , , b.... .

go2 a b -> wait for the value of b, pattern match against it, then output a:b
+1

, GHCi:

> head (go1 1 (error "urk!"))
1
> head (go2 1 (error "urk!"))
*** Exception: urk!

, go2 . go2 , go1, .

, :

fold1 go1 [] [1..] =
go1 1 (go1 2 (go1 3 ( ..... =
1 : (go1 2 (go1 3 ( ..... =
1 : 2 : (go1 3 ( ...

,

fold1 go1 [] [1..] =
go2 1 (go2 2 (go2 3 ( .....

1:..., go2 , go2, , , , , ...

, . .

+1

All Articles