Thursday, 30 May 2013

Mapping Forward, Looking Back

I’m taking things slowly.  There’s frequently a lot of meaning in very few words when learning a new (programming) language.  I’m still in Chapter 1 of Scala in Action, Nilanjan Raychaudhuri, considering the most fundamental parts.  What do I know so far?

In Scala:

“Every value is an object, and every operation is a message send.”

Scala in Action, Nilanjan Raychaudhuri, Chapter 1

Therefore what I can write in my code as 1+2 is actually interpreted by Scala as 1.+(2)

I.e. I have a value (1) and it has available functions, one of which is +.  I access these via the dot-notation (.) same as in Java and many other languages.  I then send across the argument-value by placing it within the brackets.

I can also see from this that the rules for identifiers are far more relaxed. In fact, in Scala an identifier can be made up of a sequence of 1-N letters and digits, starting with a letter, or a sequence of operator characters, so we can define methods called <=, or *.

Some more:

“[Even] functions are first class values [their italics]. That means that […] every function is a value, and like any values, you can pass them as parameters and return them from other functions.”

Scala in Action, Nilanjan Raychaudhuri, Chapter 1

NOTE 1: “Every function is a value” and not simply an object.  This is more specific.  That’s an example of what I mean about there frequently being a lot of information in a few words.

NOTE 2: In effect, function values can be sent as messages to other functions which are capable of receiving them.

So to bring it back full circle, I started out on this post from the statement:

“You can assign a function (x: Int) => x + 1 to a val inc and use that (the val) to invoke that function: inc(1)

Scala in Action, Nilanjan Raychaudhuri, Chapter 1

This had seemed like a leap to me. However, I’m mature enough now to realise that most things which look initially like big leaps, are more likely an indication that I’ve missed something earlier.  That’s what I’ve gone back and put in this post so far.  And so now, reminded of what I should have remembered the first time, does it ring true?

Well, yes, it does.  Looking at the first example, seen as the Scala compiler sees things, what we have here is a direct equivalence, only one function is called + and the other inc.  Perfectly simple.  And all making sense again.