How does ap fromMaybe compose? : <p>There I was, writing a function that takes a value as input, calls a function on that input, and if the result of that is <code>Just x</code>, it should return <code>x</code>; otherwise, it should return the original input.</p>

<p>In other words, this function (that I didn't know what to call):</p>

<pre><code>foo :: (a -&gt; Maybe a) -&gt; a -&gt; a
foo f x = fromMaybe x (f x)
</code></pre>

<p>Since it seems like a general-purpose function, I wondered if it wasn't already defined, so <a href="https://twitter.com/ploeh/status/684418608454352896">I asked on Twitter</a>, and <a href="https://twitter.com/bitemyapp/status/684467784793886720">Chris Allen replied</a> that it's <code>ap fromMaybe</code>.</p>

<p>That sounded promising, so I fired up GHCI and started experimenting:</p>

<pre><code>Prelude Control.Monad Data.Maybe&gt; :type ap
ap :: Monad m =&gt; m (a -&gt; b) -&gt; m a -&gt; m b
Prelude Control.Monad Data.Maybe&gt; :type fromMaybe
fromMaybe :: a -&gt; Maybe a -&gt; a
Prelude Control.Monad Data.Maybe&gt; :type ap fromMaybe
ap fromMaybe :: (b -&gt; Maybe b) -&gt; b -&gt; b
</code></pre>

<p>The type of <code>ap fromMaybe</code> certainly looks correct, and a couple of experiments seem to indicate that it has the desired behaviour as well.</p>

<p>But <strong>how does it work?</strong></p>

<p>The <code>fromMaybe</code> function seems clear to me, and in isolation, I think I understand what <code>ap</code> does - at least in the context of <code>Maybe</code>. When <code>m</code> is <code>Maybe</code>, it has the type <code>Maybe (a -&gt; b) -&gt; Maybe a -&gt; Maybe b</code>.</p>

<p>What I don't understand is how <code>ap fromMaybe</code> even compiles. To me, this expression looks like partial application, but I may be getting that wrong. If this is the case, however, I don't understand how the types match up.</p>

<p>The first argument to <code>ap</code> is <code>m (a -&gt; b)</code>, but <code>fromMaybe</code> has the type <code>a -&gt; Maybe a -&gt; a</code>. How does that match? Which <code>Monad</code> instance does the compiler infer that <code>m</code> is? How does <code>fromMaybe</code>, which takes two (curried) arguments, turn into a function that takes a single argument?</p>

<p>Can someone help me connect the dots?</p>
