haskell - Why is repeat defined in Prelude as it is? -


this question has answer here:

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

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -