Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>From what I understand, your layers look like:</p> <pre><code>Maybe [Maybe r] </code></pre> <p>... and you want to <code>join</code> the two <code>Maybe</code>s together, but the list is in the way. This is precisely the problem <code>sequence</code> solves:</p> <pre><code>sequence :: (Monad m) =&gt; [m r] -&gt; m [r] </code></pre> <p>Note that if we specialize <code>sequence</code> to the <code>Maybe</code> monad we get:</p> <pre><code>sequence :: [Maybe r] -&gt; Maybe [r] </code></pre> <p>In this particular case, <code>sequence</code> will return a <code>Nothing</code> if there is at least one <code>Nothing</code> in the list, but if they are all <code>Just</code>s, then it will join them all into a single <code>Just</code>.</p> <p>All that remains is to map <code>sequence</code> over the outer <code>Maybe</code>:</p> <pre><code>fmap sequence :: Maybe [Maybe r] -&gt; Maybe (Maybe [r]) </code></pre> <p>Now this is exactly in the form we need for join:</p> <pre><code>join . fmap sequence :: Maybe [Maybe r] -&gt; Maybe [r] </code></pre> <p>So, intuitively, what the above function does is that if all the inner <code>Maybe</code>s are <code>Just</code>s and the outer <code>Maybe</code> is a <code>Just</code>, then it fuses the entire result into a single <code>Just</code> containing the list. However, if any <code>Maybe</code> (either the inner ones or outer one) is a <code>Nothing</code>, the final result is a <code>Nothing</code>.</p> <p>Notice that despite doing a bunch of blind type-chasing, we ended up with a function that intuitively does the right thing. This is the power of abstractions grounded in category theory.</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