Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>How do I structure this kind of code into one which won't have a stack space problem and/or be lazy?</p> </blockquote> <p>You can't make this function process the list lazily, monads or no. Here's a direct translation of <code>countDigitsForList</code> to use pattern matching instead of <code>do</code> notation:</p> <pre><code>countDigitsForList [] = return [] countDigitsForList (x:xs) = case countDigits x of Left e -&gt; Left e Right q -&gt; case countDigitsForList xs of Left e -&gt; Left e Right qs -&gt; Right (q:qs) </code></pre> <p>It should be easier to see here that, because a <code>Left</code> at any point in the list makes the whole thing return that value, in order to determine the outermost constructor of the result, the entire list must be traversed and processed; likewise for processing each element. Because the final result potentially depends on the last character in the last string, this function as written is <em>inherently strict</em>, much like summing a list of numbers.</p> <p>Given that, the thing to do is ensure that the function is strict <em>enough</em> to avoid building up a huge unevaluated expression. A good place to start for information on that is discussions on the difference between <code>foldr</code>, <code>foldl</code> and <code>foldl'</code>.</p> <blockquote> <p>An accumulator and tail recursion seems like it may solve the problem but I repeatedly read that neither are necessary in Haskell because of lazy evaluation.</p> </blockquote> <p>Both are unnecessary when you can instead generate, process, and consume a list lazily; the simplest example here being <code>map</code>. For a function where that's not possible, strictly-evaluated tail recursion is precisely what you want.</p>
 

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