haskell - Why is repeat defined in Prelude as it is? -
this question has answer here:
- why recursive `let` make space effcient? 3 answers
repeat is defined follows:
repeat :: -> [a] repeat x = xs xs = x:xs
is there reason following isn't used?
repeat :: -> [a] repeat x = x : repeat x
(obviously there many equivalent definitions many prelude functions, latter description feels more obvious. wonder if there's performance or style reason way is.)
it performance , space complexity reasons.
the first version of code uses explicit sharing; looks one-element circular linked list in memory (the xs
in code list node has x
value , tail points same list node). when evaluate more , more elements of list take same node repeatedly.
in contrast, second version creates list grows in memory evaluated, because different invocations of repeat x
recomputed (and not memoized). there yet unevaluated thunk @ end of generated list.
Comments
Post a Comment