Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Actually, your first idea (return the counts with each value) is not a bad one, and can be expressed more abstractly by the Writer monad (in <code>Control.Monad.Writer</code> from the mtl package or <code>Control.Monad.Trans.Writer</code> from the transformers package). Essentially, the writer monad allows each computation to have an associated "output", which can be anything as long as it's an instance of <code>Monoid</code> - a class which defines:</p> <ul> <li>The empty output (<code>mempty</code>), which is the output assigned to 'return'</li> <li>An associative function (`mappend') that combines outputs, which is used when sequencing operations</li> </ul> <p>In this case, your output is a count of operations, the 'empty' value is zero, and the combining operation is addition. For example, if you're tracking operations separately:</p> <pre><code>data Counts = Counts { additions: Int, multiplications: Int } </code></pre> <p>Make that type an instance of <code>Monoid</code> (which is in the module <code>Data.Monoid</code>), and define your operations as something like:</p> <pre><code>add :: Num a =&gt; a -&gt; a -&gt; Writer Counts a add x y = do tell (Counts {additions = 1, multiplications = 0}) return (x + y) </code></pre> <p>The writer monad, together with your Monoid instance, then takes care of propagating all the 'tells' to the top level. If you wanted, you could even implement a <code>Num</code> instance for <code>Num a =&gt; Writer Counts a</code> (or, preferably, for a newtype so you're not creating an orphan instance), so that you can just use the normal numerical operators.</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. 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