title: Reverse Function Composition in Haskell
body: <p>Consider the following Haskell code:</p>
  
  <pre><code>countWhere :: (a -&gt; Bool) -&gt; [a] -&gt; Int
  countWhere predicate xs = length . filter predicate $ xs
  </code></pre>
  
  <p>In JavaScript this would be written as follows:</p>
  
  <pre><code>function countWhere(predicate, xs) {
      return xs.filter(predicate).length;
  }
  </code></pre>
  
  <p>As you can see, function composition is very similar to chaining methods in JavaScript. I really like the way chaining methods reads from left to right. In Haskell I can do something similar using the <code>&gt;&gt;&gt;</code> function from <code>Control.Arrow</code> and reverse function application as follows:</p>
  
  <pre><code>import Control.Arrow
  
  ($&gt;) :: a -&gt; (a -&gt; b) -&gt; b
  ($&gt;) = flip ($)
  
  countWhere :: (a -&gt; Bool) -&gt; [a] -&gt; Int
  countWhere predicate xs = xs $&gt; filter predicate &gt;&gt;&gt; length
  </code></pre>
  
  <p>Now I want to write this function in point free style. Using function composition I would write it as follows:</p>
  
  <pre><code>(.:) :: (b -&gt; c) -&gt; (d -&gt; a -&gt; b) -&gt; d -&gt; a -&gt; c
  (.:) = (.) (.) (.)
  
  countWhere ::  (a -&gt; Bool) -&gt; [a] -&gt; Int
  countWhere = length .: filter
  </code></pre>
  
  <p>However I would like to write this function in point free style using reverse function composition as follows:</p>
  
  <pre><code>(.:) :: (b -&gt; c) -&gt; (d -&gt; a -&gt; b) -&gt; d -&gt; a -&gt; c
  (.:) = (.) (.) (.)
  
  (:.) :: (d -&gt; a -&gt; b) -&gt; (b -&gt; c) -&gt; d -&gt; a -&gt; c
  (:.) = flip (.:)
  
  countWhere :: (a -&gt; Bool) -&gt; [a] -&gt; Int
  countWhere = filter :. length
  </code></pre>
  
  <p>My gripe is that I have to define the <code>:.</code> function in terms of function composition instead of reverse function composition. That is:</p>
  
  <pre><code>(:.) = flip $ (.) (.) (.)
  
  -- instead of
  
  (:.) = (&gt;&gt;&gt;) (&gt;&gt;&gt;) (&gt;&gt;&gt;)
  </code></pre>
  
  <p>Of course <code>(&gt;&gt;&gt;) (&gt;&gt;&gt;) (&gt;&gt;&gt;)</code> is of the wrong type. It's not the function that I am looking for.</p>
  
  <p>The beauty of function composition is that it can be composed with itself to form "higher order function compositions" as demonstrated above. Hence although its type signature is intuitively backwards it's actually forward, which explains why <code>f . g = \x -&gt; f (g x)</code> instead of <code>f . g = \x -&gt; g (f x)</code>.</p>
  
  <p>This brings me to my actual question: is there any way to define "higher order reverse function compositions" in terms of reverse function composition (i.e. <code>&gt;&gt;&gt;</code>) instead of <code>flip</code>ing the corresponding "higher order function compositions"?</p>
  
  <p>I'm looking for an answer that has its roots in either Category Theory or other branches of Mathematics.</p>