title: How to write a Haskell Pipes "sum" function?
body: <p>I'm trying to learn the <code>pipes</code> package by writing my own <code>sum</code> function and I'm getting stumped. I'd like to not use the utility functions from <code>Pipes.Prelude</code> (since it has <code>sum</code> and <code>fold</code> and other functions which make it trivial)  and only use the information as described in <code>Pipes.Tutorial</code>. The tutorial doesn't talk about the constructors of <code>Proxy</code>, but if I look in the source of <code>sum</code> and <code>fold</code> it uses those constructors and I wonder whether it is possible to write my <code>sum</code> function without knowledge of these low level details.</p>
  
  <p>I'm having trouble coming to terms with how this function would be able to continue taking in values as long as there are values available, and then somehow return that sum to the user. I guess the type would be:</p>
  
  <pre><code>sum' :: Monad m =&gt; Consumer Int m Int
  </code></pre>
  
  <p>It appears to me this could work because this function could consume values until there are no more, then return the final sum. I would use it like this:</p>
  
  <pre><code>mysum &lt;- runEffect $ inputs &gt;-&gt; sum'
  </code></pre>
  
  <p>However, the function in <code>Pipes.Prelude</code> has the following signature instead:</p>
  
  <pre><code>sum :: (Monad m, Num a) =&gt; Producer a m () -&gt; m a
  </code></pre>
  
  <p>So I guess this is my first hurdle. Why does the <code>sum</code> function take a <code>Producer</code> as an argument as opposed to using <code>&gt;-&gt;</code> to connect?</p>
  
  <hr>
  
  <p>FYI I ended up with the following after the answer from danidiaz:</p>
  
  <pre><code>sum' = go 0
    where
      go n p = next p &gt;&gt;= \x -&gt; case x of
        Left _        -&gt; return n
        Right (_, p') -&gt; go (n + 1) p'
  </code></pre>