Search code examples
haskelltying-the-knot

Why doesn't `iterate` from the Prelude tie the knot?


Why isn't iterate defined like

iterate :: (a -> a) -> a -> [a]
iterate f x = xs where xs = x : map f xs

in the Prelude?


Solution

  • Tying the knot like that doesn't appear to increase sharing.

    Contrast with:

    cycle xs = let x = xs ++ x in x
    

    Tying the knot here has the effect of creating a circular linked list in memory. x is its own tail. There's a real gain.

    Your suggested implementation doesn't increase sharing over the naive implementation. And there's no way for it to do so in the first place - there's no shared structure in something like iterate (+1) 0 anyway.