Are summer songs for me and my aunts"
Shakespeare, The Winter's Tale
Act IV, Scene III, Lines 10-11
As the wind gently rustles the leaves in the combinator forest. You sing DO RA and hear sung back to you RA DO. You sing RA ME and hear ME RA, you sing DO DO and hear DO DO back. You have just heard the Thrush.
The Thrush or T combinator basically flips your parameters.
T x f = f x
In the Data Aviary Bird package for Haskell it is defined in the following way:
-- | T combinator - thrush. -- Haskell @(\#)@ in Peter Thiemann\'s Wash, reverse application. thrush :: a -> (a -> b) -> b thrush x f = f x
We see that when we call it we pass a value as our first parameter followed by the function we wish to apply the value against. This is useful when you want to pipe your data through a bunch of functions.
Thrush in F#
In fact in F# this is exactly what the |> (forward pipe) does. It is defined in the following way:
let (|>) x f = f x
Yep, the forward pipe is nothing more than a Thrush!
Thrush in Joy
[B] [A] swap == [A] [B]
This exactly what we would expect looking at the Haskell and F# code above.
This is very similar to how Reginald defined the Thrush in Ruby in his excellent book, Kestrels, Quirky Birds, and Hopelessly Egocentricity:
Thrush(y) in Clojure
Clojure has two macros which are Thrushy (Michael Fogus has an excellent post on why they are Thrushy) the -> and ->> macros.
Say we wanted to do the following:
get the sum of the even integers from 1 to 100
We can break this requirement down into a few steps.
- get the integers from 1 to 100
- get the even integers from 1
- sum the integers from 2
What we see happening is a linking or piping of the results of a step down to the next step.
1 to 100 => evens => sum
Here are two ways to write this in Clojure:
The first way looks like a waterfall, but in order to understand it we need to go all the way to the bottom and work are way back up. In this example we would start with the (range 101) then move up to the (filter even?) and lastly end at the (reduce +). We find that reading this, we are going against the left to right flow of the code.
The second, Thrush(y) way, the first thing we see is our (range 101), next we find the (filter even?), and last we find the (reduce +). This way seems very natural as the flow of data agrees with the reading from left to right.
I personally find the pipeline style used in the second way easier to read and use it as often as I can. Martin Folwer has written an excellent article which goes into collection pipelines in more detail. Debasish Ghosh has also written about the Thrush in Clojure (which help me a lot when I was trying to understand the -> and ->>macros).