Tuesday, 21 May 2013

Higher Order Functions <gulp/>

The time has come to tackle my sparse knowledge of the Functional Idiom head on.  I was googling “computer science map function” to try and get my head round the impending mental traffic accident between me and the Scala Collections APIs.  I found what I was looking for right away but it seemed that to take the first step up to grokking this Functional thing, I should bite the bullet and try and read the Higher-Order Function page.  Whoosh! Right in at the deep end. Let’s go.

“a higher-order function (also functional form, functional or functor) is a function that does at least one of the following:

  • take one or more functions as an input
  • output a function”

That makes sense.  The Scala map function clearly takes a function as an input parameter (for example).

I’ll skip the next bit as it was gobbldigook (perhaps I’ll be able to make sense of it later down the line) but I picked up the thread again two paragraphs later:

“The map function, found in many functional programming languages, is one example of a higher-order function. It takes as arguments a function f and a list of elements, and as the result, returns a new list with f applied to each element from the list.”

Brilliant.  That makes perfect sense too, and we’re using my personal bugbear as the example.  I’m beginning to see why “map” isn’t such a stumbling block to everyone else. If only I’d studied Computing Science at University… Lets read on.

Right, next came a lot of examples in programming languages I’ve not used (or actively avoid – sorry JavaScript). I’m tempted to write a Scala-equivalent of one of them, but I think it’d be jumping the gun a little.  Instead, lets read the “Alternatives” section as it seems to start speaking my language:

“In object-oriented programming languages that do not support higher-order functions, objects can be an effective substitute. An object's methods act in essence like functions, and a method may accept objects as parameters and produce objects as return values. Objects often carry added run-time overhead compared to pure functions, however, and added boilerplate code for defining and instantiating an object and its method(s).”

Now that makes perfect sense to me.  It’s one of the reasons I’ve wanted to get on board with Scala.  It feels like we’re getting somewhere.  In the next post I’ll dip back down to “Map” and perhaps even “Fold” and see what these words mean to these crazy computing scientists.