Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>pelotom's answer is the straightforward one. But not the fun one! <code>sequence</code> is the Haskell function that one can think of as flipping the order of type constructors between a list and a monad. </p> <p><code>sequence :: (Monad m) =&gt; [m a] -&gt; m [a]</code></p> <p>Now what you want is, so to speak, to flip the order of type constructors between a <code>Maybe</code> and a monad. Data.Traversable exports a <code>sequence</code> function with just that capacity!</p> <p><code>Data.Traversable.sequence :: (Traversable t, Monad m) =&gt; t (m a) -&gt; m (t a)</code></p> <p>This can specialize to <code>Maybe (IO ()) -&gt; IO (Maybe ())</code> like in your example.</p> <p>Hence: </p> <pre><code>Prelude Data.Traversable&gt; Data.Traversable.sequence (fmap print $ Nothing) Nothing Prelude Data.Traversable&gt; Data.Traversable.sequence (fmap print $ Just 123) 123 Just () </code></pre> <p>Note that there's also a <code>sequenceA</code> function which is slightly more general, working not just on Monads but all Applicatives.</p> <p>So why use this approach? For <code>Maybe</code> the approach that takes it apart explicitly is fine. But what about a bigger data structure -- a <code>Map</code> for example? In that case, <code>traverse</code>, <code>sequenceA</code> and friends from <code>Data.Traversable</code> can be real handy.</p> <p>Edit: as Ed'ka notes, <code>traverse :: Applicative f =&gt; (a -&gt; f b) -&gt; t a -&gt; f (t b)</code> and so one can just write <code>traverse print $ Just 123</code>.</p>
 

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