[Haskell-cafe] Maintaining laziness: another example

Martijn van Steenbergen martijn at van.steenbergen.nl
Mon Jun 8 08:05:27 EDT 2009


Hello,

While grading a Haskell student's work I ran into an example of a 
program not being lazy enough. Since it's such a basic and nice example 
I thought I'd share it with you:

One part of the assignment was to define append :: [a] -> [a] -> [a], 
another to define cycle2 :: [a] -> [a]. This was her (the majority of 
the students in this course is female!) solution:

> append :: [a] -> [a] -> [a]
> append [] ys = ys
> append xs [] = xs
> append (x:xs) ys = x : (append xs ys)
> 
> cycle2 :: [a] -> [a]
> cycle2 [] = error "empty list"
> cycle2 xs = append xs (cycle2 xs)

This definition of append works fine on any non-bottom input (empty, 
finite, infinite), but due to the unnecessary second append case, cycle2 
never produces any result.

Martijn.


More information about the Haskell-Cafe mailing list