title: Function as an Instance of Monad
body: <p>I am having difficulty understanding how a function can be a monad.</p>
  
  <p>Function <code>(-&gt;) r</code> is a monad according to a declaration in <code>Control.Monad.Instances</code>:</p>
  
  <pre><code>instance Monad ((-&gt;) r) where  
      return x = \_ -&gt; x  
      h &gt;&gt;= f = \w -&gt; f (h w) w  
  </code></pre>
  
  <p>Even what Miran Lipovača <a href="http://learnyouahaskell.com/for-a-few-monads-more#state">says</a> about it makes me confused:</p>
  
  <blockquote>
    <p>The implementation for <code>&gt;&gt;=</code> seems a bit cryptic, but it's really not
    all that. When we use <code>&gt;&gt;=</code> to feed a monadic value to a function, the
    result is always a monadic value. So in this case, when we feed a
    function to another function, the result is a function as well. That's
    why the result starts off as a lambda. All of the implementations of
    <code>&gt;&gt;=</code> so far always somehow isolated the result from the monadic value and then applied the function f to that result. The same thing happens
    here. To get the result from a function, we have to apply it to
    something, which is why we do <code>(h w)</code> here to get the result from the
    function and then we apply f to that. f returns a monadic value, which
    is a function in our case, so we apply it to w as well.</p>
  </blockquote>
  
  <p>The type signature of (>>=) is this:
          (>>=) :: m a -> (a -> m b) -> m b</p>
  
  <p>So I take that <code>h</code> is typed as <code>m a</code> and <code>f</code> as <code>(a -&gt; m b)</code>.  If a function is <code>m a</code>, does it return an <code>a</code> type value?  or does it return something else taking an <code>a</code> type?</p>
  
  <p>If the non-monad value of <code>h</code> is fed to <code>f</code>, then we get:
          f (h w)
  Looks fine.  Since <code>f</code> is a function and has taken its sole argument, it is already a value, no?  Since it's a monadic function the value is also a monadic value.  Why then does it need another value <code>w</code>?  Doesn't feeding <code>w</code> to <code>f something</code> make it non-monadic, i.e., it is not a function any more, no?  I also cannot understand why <code>f something</code> and <code>h</code> take the same argument <code>w</code> and return different value types (<code>m a</code> and <code>m b</code>).</p>