Wednesday, 11 September 2013

Pattern Matching, Take 2, Part 1

Things are about to get interesting.  I’ve made it to the point in Atomic Scala where Bruce (Eckel) and Dianne (Marsh) recommend you jump in if you're proficient in another language (not me, hopefully) or if you didn’t want to make damn certain you grokked the basics, before moving onto the core stuff (definitely me).  So what’s up? Pattern Matching that’s what’s up.

The first time I came across the Pattern Matching Syntax, like many things in Scala, I wasn’t a fan. I’m rapidly coming to the conclusion however that this initial revulsion is the way things are normally presented, rather than the syntax itself.  My primary requirement (in order for it to enter my head and slosh around up there accruing supporting information) is that it reads.  That’s one of Dianne and Bruce’s strengths; the first encounters with new syntactical elements always serves as a way to “read it to yourself in your head”. For example, you could narrate their introductory example on pp130 as:

“take this color [sic] object and match it to these cases: ({)
    in the case when it’s “red” => then produce result “RED”
    in the case when it’s “blue” => then produce result “BLUE”
    in the case when it’s “green” => then produce result “GREEN”
    and in the case when it’s anything else (_) => then produce result “UNKNOWN COLOR: ” + color”

That feels right to me. i know it can get a helluva lot more complicated, but to have that basic understanding to hang my hat on helps a lot.  Helpfully Bruce and Dianne also signpost specifically where things are going to get hairy later on. But I don’t have to worry about that yet.  First I’ve got the exercises to cement things.

No comments:

Post a Comment