It’s easiest to understand with pictures:
-
The first version
repeat x = x : repeat xcreates a chain of
(:)constructors ending in a thunk which will replace itself with more constructors as you demand them. Thus, O(n) space.
-
The second version
repeat x = let xs = x : xs in xsuses
letto “tie the knot”, creating a single(:)constructor which refers to itself.