[Haskell-cafe] infinite lists

Matthias Fischmann fis at wiwi.hu-berlin.de
Tue Mar 27 05:52:13 EDT 2007



hi,

it just took me an eternity to undestand a bug in my code *after* i
had narrowed it down to eight lines or so.  and as these bugs go, i
feel very good about having found it and have to share it.  although
it's probably not that exciting to anybody except me.  (-:

here is the bug, narrowed to four lines.  a function that only
sometimes terminates.

f = do
    n <- randomRIO (0,5)
    let l = replicate n '*'
        i = join $ repeat l  -- infinite extension
    print (take 12 i)

how many seconds does it take you to shout "you idiot!"?  :-) spoiler
below.  (what would have been your fix?)

cheers,
matthias












































































































































































































































































































===================================================================
spoiler.  the problem is that l is sometimes empty, and taking an
element out of an infinite concatenation of empty lists takes even
longer than understanding that that takes quite long.  just deal with
the empty-list case separately:

g = do
    n <- randomRIO (0,5)
    let l = replicate n '*'
        i | null l = []
          | otherwise = join $ repeat l
    print (take 12 i)


More information about the Haskell-Cafe mailing list