[newbie] Lazy >>= ?!

Scott Turner p.turner@computer.org
Sat, 17 Feb 2001 15:44:32 -0500

Andrew Cooke wrote:
>2.  Why does the following break finite lists?  Wouldn't they just
>become lazy lists that evaluate to finite lists once map or length or
>whatever is applied?
>> Now, if this were changed to 
>>     ~(x:xs) >>= f = f x ++ (xs >>= f)
>> (a lazy pattern match) then your listList2 would work, but finite
>> lists would stop working.

They wouldn't just become lazy lists.  A "lazy" pattern match isn't about
removing unnecessary strictness.  It removes strictness that's necessary
for the program to function normally.  A normal pattern match involves
selecting among various patterns to find the one which matches; so it
evaluates the expression far enough to match patterns.  In the case of
it must evaluate the list sufficiently to know that it is not an empty
list.  A lazy pattern match gives up the ability to select which pattern
matches.  For the sake of less evaluation, it opens up the possibility of a
runtime error, when a reference to a named variable won't have anything to
bind to.

The list monad is most often used with complete finite lists, not just
their initial portions.  The lazy pattern match shown above breaks this
because as it operates on the list, it assumes that the list is non-empty,
which is not the case when the end of the list is reached.  A runtime error
is inevitable. 

Scott Turner
p.turner@computer.org       http://www.billygoat.org/pkturner