Understanding Currying with Scala

The first time I learned about currying is when I tried Haskell. Back then, I thought that currying is just a gimmick, nice but has no practical use. How wrong was I. Of course, Haskell code examples must be glaringly showing me some cool uses of currying back then. It must be me who was lost, too busy trying to grasp the unfamiliar syntax and missed the lights.

Then, several days ago I started to play with Scala. Actually the first time I encountered Scala was even before that, but my first impression was, well, unimpressed, just because I saw type declarations scattered here and there (yes, I’m a duck-man). Fortunately for the second “date”, I was able to see through those nasty ugliness (I insist :p).

The following code is taken from Scala by Example, a quicksort implementation:

def sort(xs: Array[Int]): Array[Int] = {
    if (xs.length <= 1) xs
    else {
        val pivot = xs(xs.length / 2)
            sort(xs filter (pivot >)),
            xs filter (pivot ==),
            sort(xs filter (pivot <))

The line 6-8 provoked my thought:

    sort(xs filter (pivot >)),
    xs filter (pivot ==),
    sort(xs filter (pivot <)))

That’s, like, ultra-neat! At first I thought it was just syntactic sugar, but how does it work? Well it does involve syntactic sugar: in scala, xs filter something is syntactic sugar for xs.filter(something). OK but how about the something part? It turned out that in Scala many operators are actually method, so x < y is really x.<(y). Neat. One puzzle remain: the pivot <, pivot ==, and pivot >. Another syntactic sugar? I thought so, but I couldn’t find the explanation. It looks unfinished. Yeah, like missing the argument. Like, wait, what was that gimmicky thing I in Haskell again?

Whoa, currying!
That partially-applied-function-returns-function thing!

So, pivot < means pivot.<() and since < needs one argument but given none, it instead returns another function that accepts the missing argument: the number to be compared. So the something given to filter is a function. Now that makes sense. Puzzle solved. Scala is cool.

And currying rocks!


3 thoughts on “Understanding Currying with Scala

  1. Pingback: Function Currying in Scala – Part 4 | Solution Hacker

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s