Tuesday, March 9, 2010

Curried and Confused

In the article Curried and Confused on coderspiel the author gives us this example of Scala code that people supposedly think is too difficult for regular folks:

def sum(nums: List[Int]) = (0 /: nums) { _ + _ }

He then goes on to say that it might be because of the /: symbol, but that this version does not make it any better:

def sum(nums: List[Int]) = (nums foldLeft 0) { _ + _ }

And this is the point where we differ completely. For me if the first version hadn't been called "sum" I would have had no idea what the code does. The moment I read the second version and I saw "foldLeft" I knew this was about an application of some function to a list of numbers resulting in a single result (hence the folding).

For me this isn't about reading (nums foldLeft 0) and not knowing it's the same as nums.foldLeft(0), you learn that once when reading about Scala's syntax and it will stick. Maybe you need to think about it a bit more the first couple of times, but it's not hard, the basics are still the same, the order is still the same, you can still think: "I've got this object nums on which I'm going to perform a foldLeft and... what's this 0 here? Oh must be an argument".

It also isn't about the whole closure bit where you suddenly see braces at the end of a statement, because getting used to Functional Programming you know that this is normally part of this brand new toolbox you've got. The _ + _ part does pose a bit of a problem for Scala first-timers, I agree.

But in the end for me the real problem is this /: symbol. What does it mean? If I see it, it doesn't ring any bells! There is no mathematical symbol that looks like this, in fact it looks like the symbol we've been using for ages now to denote division!

This is about readability, I always agreed with the Java-tenet where they would say that you tend to read code many many more times than that you write it. And it might be read by many people who don't have a way to look into your mind so it's important to write code in a way that it's function is as obvious as possible.

/: is NOT obvious.

But reading foldLeft is, once you've read at least once about folding and what it is used for. Because it doesn't matter in the end which language you use to implement the folding, it's a concept that's easy to grasp, but what happens if you have to go and learn by heart all the strange symbols that one can come up with? Especially when each language decides to use different symbols to express the same thing.

I now understand why they left out operator overloading in Java.
(yes, I know that in Scala this is not operator overloading strictly speaking, take your nitpicking somewhere else)

No comments:

Post a Comment