title: Haskell - Evaluation of (+) <$> (+3) <*> (*100) $ 5
body: <p><a href="http://learnyouahaskell.com/functors-applicative-functors-and-monoids">From the chapter on Functors in Learn You a Haskell for Great Good</a>, Lipovača states:</p>
  
  <blockquote>
    <p>"When we do <code>(+) &lt;$&gt; (+3) &lt;*&gt; (*100)</code>, we're making a function that will use <code>+</code> on the results of <code>(+3)</code> and <code>(*100)</code> and return that. To demonstrate on a real example, when we did <code>(+) &lt;$&gt; (+3) &lt;*&gt; (*100) $ 5</code>, the <code>5</code> first got applied to <code>(+3)</code> and <code>(*100)</code>, resulting in <code>8</code> and <code>500</code>. Then, <code>+</code> gets called with <code>8</code> and <code>500</code>, resulting in <code>508</code>."</p>
  </blockquote>
  
  <p>However, if I try to evaluate the function myself, considering this definition for Applicative on the functor ((->) r):</p>
  
  <pre><code>instance Applicative ((-&gt;) r) where  
      pure x = (\_ -&gt; x)  
      f &lt;*&gt; g = \x -&gt; f x (g x)  
  </code></pre>
  
  <p>I read the evaluation of the above expression as:</p>
  
  <p><code>(\x -&gt; (3 + x) (100 * x)) $ 5</code></p>
  
  <p>But I don't see how we can compose two partially applied binary functions as a single lambda (in fact, GHCi throws an infinite type error trying to bind this to a variable). Furthermore, to a working interpretation, if we look at the type definition for <code>&lt;$&gt;</code> we get:</p>
  
  <p><code>(&lt;$&gt;) :: Functor f =&gt; (a -&gt; b) -&gt; f a -&gt; f b</code></p>
  
  <p>or more specifically we can look at its lifting as:</p>
  
  <p><code>(&lt;$&gt;) :: Functor f =&gt; (a -&gt; b) -&gt; (f a -&gt; f b)</code></p>
  
  <p>Considering that our functor in this case is ((->) r), I can deduce that this is what transformation takes place on the previous evaluation (assuming that left associativity happens first, instead of the right associative application of <code>5</code>):</p>
  
  <p><code>(\x -&gt; a + b)</code> where <code>a</code> = <code>(+ 3)</code> and <code>b</code> = <code>(* 100)</code>. This is the function that should be returned. However, am I correct in assuming that this is the final (rough) form?</p>
  
  <p><code>(\x -&gt; (3 + x) + (100 * x)) $ 5</code></p>
  
  <p>...which yields 508.</p>
  
  <p>I find Lipovača's description more comprehensible in terms of how the expression works, but my gut tells me isn't entirely true for the gorey details under the Haskell compiler hood. It is easier for me to think that the fmap of (+) happened first resulting in a function with two functors who are partially applied functions that take a shared input, and then we applied a value to it. We can do this because of lazy evaluation. Is this wrong?</p>