Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This puts one in mind of <code>sigfpe</code>'s <a href="http://blog.sigfpe.com/2006/08/you-could-have-invented-monads-and.html" rel="noreferrer">illustration of the so-called Writer monad</a>. You might do it a bit more systematically like this:</p> <pre><code>import Control.Monad.Trans.Writer import Control.Monad.Trans import Data.Monoid fibwriter :: Int -&gt; Writer (Sum Int) Integer fibwriter 0 = return 0 fibwriter 1 = return 1 fibwriter n = do a &lt;- fibwriter (n-1) b &lt;- fibwriter (n-2) tell (Sum (2::Int)) return (a + b) </code></pre> <p>Used thus:</p> <pre><code>*Fib&gt; runWriter $ fibwriter 11 (89,Sum {getSum = 286}) </code></pre> <p>This is the same definition, but with the 'side effect' of logging each additional pair of recursions. We can also add a side effect in <code>IO</code> if we want to see all the crazy recalculation involved in the 'naive' definition while it happens:</p> <pre><code>fibprint :: Int -&gt; WriterT (Sum Int) IO Integer fibprint 0 = return 0 fibprint 1 = return 1 fibprint n = do a &lt;- fibprint (n-1) record a b &lt;- fibprint (n-2) record b return (a + b) where record x = lift (putStr $ ' ' : show x) &gt;&gt; tell (Sum 1) </code></pre> <p>For fibonacci 11 this gives us this absurdly repetitious show, as the calculation climbs toward 89:</p> <pre><code>*Fib&gt; runWriterT $ fibprint 11 1 0 1 1 2 1 0 1 3 1 0 1 1 2 5 1 0 1 1 2 1 0 1 3 8 1 0 1 1 2 1 0 1 3 1 0 1 1 2 5 13 1 0 1 1 2 1 0 1 3 1 0 1 1 2 5 1 0 1 1 2 1 0 1 3 8 21 1 0 1 1 2 1 0 1 3 1 0 1 1 2 5 1 0 1 1 2 1 0 1 3 8 1 0 1 1 2 1 0 1 3 1 0 1 1 2 5 13 34 1 0 1 1 2 1 0 1 3 1 0 1 1 2 5 1 0 1 1 2 1 0 1 3 8 1 0 1 1 2 1 0 1 3 1 0 1 1 2 5 13 1 0 1 1 2 1 0 1 3 1 0 1 1 2 5 1 0 1 1 2 1 0 1 3 8 21 55 1 0 1 1 2 1 0 1 3 1 0 1 1 2 5 1 0 1 1 2 1 0 1 3 8 1 0 1 1 2 1 0 1 3 1 0 1 1 2 5 13 1 0 1 1 2 1 0 1 3 1 0 1 1 2 5 1 0 1 1 2 1 0 1 3 8 21 1 0 1 1 2 1 0 1 3 1 0 1 1 2 5 1 0 1 1 2 1 0 1 3 8 1 0 1 1 2 1 0 1 3 1 0 1 1 2 5 13 34(89,Sum {getSum = 286}) </code></pre>
 

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