title: Using Maybe and Writer together
body: <p>Here is my egg packing factory:</p>
  
  <pre><code>type Eggs = Int
  data Carton = Carton Eggs deriving Show
  
  add :: Eggs -&gt; Carton -&gt; Maybe Carton
  add e (Carton c)
      | c + e &lt;= 12 = Just (Carton $ c + e)
      | otherwise = Nothing
  
  main = do
      print $ pure(Carton 2) &gt;&gt;= add 4 &gt;&gt;= add 4 &gt;&gt;= add 3
  </code></pre>
  
  <p>Seems to work well, I can nicely chain <code>add</code> functions.</p>
  
  <p>But I want to record a log of how many eggs were added at every step. So I do this:</p>
  
  <pre><code>import Control.Monad.Writer
  
  type Eggs = Int
  data Carton = Carton Eggs deriving Show
  
  add :: Eggs -&gt; Carton -&gt; Writer [String] (Maybe Carton)
  add e (Carton c)
      | c + e &lt;= 12 = do
          tell ["adding " ++ show e]
          return (Just (Carton $ c + e))
      | otherwise = do
          tell ["cannot add " ++ show e]
          return Nothing
  
  main = do
      let c = add 4 $ Carton 2
      print $ fst $ runWriter c
      mapM_ putStrLn $ snd $ runWriter c
  </code></pre>
  
  <p>This gives me what I want: I can see the resulting carton and the record for 4 eggs being added.</p>
  
  <p>But I seem to have lost the ability to chain <code>add</code> functions like I did before:</p>
  
  <pre><code>let c = pure(Carton 2) &gt;&gt;= add 4 -- works
  let c = pure(Carton 2) &gt;&gt;= add 4 &gt;&gt;= add 2 -- does not work
  </code></pre>
  
  <p>How can I chain my new writer-enabled <code>add</code> functions? Is there a better way of doing this?</p>