Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I agree with <a href="https://stackoverflow.com/users/98117/hammar">hammar</a>, <a href="https://stackoverflow.com/questions/16870683/avoid-pattern-matching-in-recursion#comment24338245_16870930"><code>unfoldr</code> is the way to go here</a>.</p> <p>You can also get rid of the pattern matching in <code>diagNums</code>:</p> <pre><code>diagNums = go skips 2 where go (s:skips) x = let x' = x+s in x':go skips (x'+1) </code></pre> <p>The recursion makes it a little difficult to tell what's going on here, so let's examine it in depth.</p> <p>Suppose <code>skips = s0 : s1 : s2 : s3 : ...</code>, then we have:</p> <pre><code>diagNums = go skips 2 = go (s0 : s1 : s2 : s3 : ...) 2 = s0+2 : go (s1 : s2 : s3 : ... ) (s0+3) = s0+2 : s0+s1+3 : go (s2 : s3 : ... ) (s0+s1+4) = s0+2 : s0+s1+3 : s0+s1+s2+4 : go (s3 : ... ) (s0+s1+s2+5) = s0+2 : s0+s1+3 : s0+s1+s2+4 : s0+s1+s2+s3+5 : go (...) (s0+s1+s2+s3+6) </code></pre> <p>This makes it much clearer what's going on, we've got the sum of two sequences, which is easy to compute using <code>zipWith (+)</code>:</p> <pre><code>diagNums = zipWith (+) [2,3,4,5,...] [s0, s0+s1, s0+s1+s2, s0+s1+s2+s3,...] </code></pre> <p>So now we just need to find a better way to compute the partial sums of <code>skips</code>, which is a great use for <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:scanl1" rel="nofollow noreferrer"><code>scanl1</code></a>:</p> <pre><code>scanl1 (+) skips = s0 : s0+s1 : s0+s1+s2 : s0+s1+s2+s3 : ... </code></pre> <p>Leaving a (IMO) much easier to understand definition for <code>diagNums</code>:</p> <pre><code>diagNums = zipWith (+) [2..] $ scanl1 (+) skips </code></pre>
    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. 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.
    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