This blog post was originally posted on my blogpost blog at this URL, and was later migrated to this place. There may be some comments at the original URL.
Haskell due to the curried nature of its functions makes partial application and composition a favorable programming style. A few days ago, I solved Project Euler problem #52 with the following elegant code:
In some cases though, composition with
(.) alone does not yield very readable expressions.
Let’s take an example. Consider the following function:
How do you write that with
(.)? Intuition might suggest the following will work:
But it doesn’t. The reason is currying. The type signatures of
As you cans see, result type of filter,
([a] -> [a]) is not compatible with input type of length,
[a]. The types will comply when filter is partially applied on one argument. So this is how we can rewrite
That still leaves us with one point. This is not a problem in languages like Clojure, where functions are not curried.
Let’s ask lambdabot how to get rid of that point.
And yay, the point is gone!
This pattern generalizes nicely for higher adicities. For example,
However that isn’t very readable. We can capture these composition patterns in new combinators like shown below:
With these we can rewrite as follows the expressions we saw before:
For each adicity
n, we will have to write a separate combinator,
composen. It is not possible to generalize them into one combinator.