Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This doesn't stack overflow - even in the interpreter, where there are no optimizations and no rewrite rules - because it doesn't use the stack.</p> <p>Look at the definition of (++), for example,:</p> <pre><code>(++) :: [a] -&gt; [a] -&gt; [a] (++) [] ys = ys (++) (x:xs) ys = x : xs ++ ys </code></pre> <p>The key thing is <code>x : (xs ++ ys)</code> -- that is, it is recursion guarded by the (:) "cons" constructor. Because Haskell is lazy, it allocates a thunk for the cons operation, and the recursive call goes onto this (heap-allocated) thunk. So your stack allocation is now heap allocation, which can expand quite a bit. So all this does is walk the big list, allocating new cons objects on the heap to replace the ones it is traversing. Easy!</p> <p>"reverse" is a bit different:</p> <pre><code>reverse l = rev l [] where rev [] a = a rev (x:xs) a = rev xs (x:a) </code></pre> <p>That is a tail recursive, accumulator-style function, so again, it will allocate on the heap.</p> <p>So you see, the functions rely on using cons cells on the heap, instead of on the stack, hence no stack overflow.</p> <p>To really nail this, look at the runtime stats from the GC vm:</p> <pre><code>$ time ./B +RTS -s 99 833 MB total memory in use (13 MB lost due to fragmentation) Generation 0: 3054 collections, 0 parallel, 0.99s, 1.00s elapsed %GC time 82.2% (85.8% elapsed) </code></pre> <p>There's your big list -- it is allocated on the heap, and we spend 80% of the time cleaning up cons nodes that are created by (++).</p> <p>Lesson: you can often trade stack for heap.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload