Syntax Collisions

The Scala icon-external-link-12x12 icon-search-12x12 programming language is filled with all kinds of syntax abbreviations that can do a lot to make code clean, concise, and explicit. Typically these are useful and intuitive for someone who is familiar with the core language, but there are some that could be called cryptic, and maybe even deceptive. The following example is provided by the book Programming in Scala icon-external-link-12x12 icon-search-12x12 during a lesson on Pattern Matching icon-external-link-12x12 icon-search-12x12, and the authors may have omitted necessary explanations in previous sections for the reader to make successful attempts at its interpretation:

val withDefault: Option[Int] => Int = {
  case Some( x ) => x
  case None => 0
}

At first glance, the code looks very much like a variable declaration that collided with a function definition resulting in a new combined entity and some shrapnel (appearing in the form of Int = ). This is actually a function that returns an instance of Int, which is confirmed by its behavior:

scala> withDefault( Some( 10 ) )
res28: Int = 10

scala> withDefault( None )
res29: Int = 0

So it’s clear that withDefault is the variable’s name, but is it somehow also the type Option[Int]? This cannot be, but it is way too close to a variable declaration for comfort. So what’s going on? And if pattern matching is occurring—which it is—where did the match statement go?

It turns out the above function literal is shorthand for the following:

val withDefault = ( argument: Option[Int] ) => argument match {
  case Some( x ) => x
  case None => 0
}

This is unambiguous, while the abbreviated version is not: argument is supplied to the function referenced by the withDefault variable and then matching attempts are made against the cases Some(x) and None with either x or 0 being returned, depending on the match that is made. It’s also not that much longer, which makes a person wonder why the shorthand version was included in the language at all.

As a final note, the abbreviated form behaves the same as the following function literal, which uses Scala’s Placeholder Syntax icon-external-link-12x12 icon-search-12x12 to unshroud the argument:

val withDefault: Option[Int] => Int = {
  _ match {
    case Some( x ) => x
    case None => 0
  }
}

So the mystery has been solved, and it’s probably safe to say that this is not one of Scala’s better syntax maneuvers. The piece of code shrapnel Int = is the only oddity that remains, and this is present because the compiler needs the return type to be specified. Why can’t it make this inference in the original function when it was able to do so in the second and more reasonable definition? Fuck if I know. Maybe the compiler needs a token to appear there so that nonsense like => = doesn’t ever have to be considered valid. Regardless, this sure seems like a lot of trouble to save the programmer from typing a few extra characters on the keyboard.

Ruminant Ruminations

After spending the weekend poring over programming texts and technical articles, I brought up a dictionary website to quickly investigate the subtle but very important difference in meaning between the words superfluous icon-external-link-12x12 and extraneous icon-external-link-12x12. I take notes when I am studying and regard each unfilled Post-it as an opportunity to better articulate whatever idea is being presented to me by an author. Aside from being an effective learning device that also enhances a book’s usefulness as a reference, this approach makes it possible to gauge the overall quality of the source material. In general, extra work done on my part to complete a lesson exposes a book’s incompleteness. In this particular case, I was not correcting the author or expounding an idea but simply augmenting the original statement, which went something like this: in a Java program, writing a subclass can be superfluous—and not extraneous—when an anonymous class can be used instead. Here is the code-representation of a pen, the well known and commonplace writing utensil, and how it’s behavior can be changed in a computer program using an anonymous class:

class Pen {
  public void write() {
    System.out.println( "Writing with a pen!" );
  }
}

class Lecture {
  // COMMENT:  This anonymous class produces cleaner code by
  //   extending the Pen class and overriding its procedure
  //   write(), giving it new behavior.
  Pen pen = new Pen () {
    public void write() {
      System.out.println( "Writing with a pen in a lecture!" );
    }
  };
}

Like any popular dictionary website, the one I frequent provides a Word of the Day on the front page. The appeal of a Word of the Day showcase is that people find it entertaining to discover words that they have never or rarely seen or heard before. Normally this is just for entertainment, but some people take it too far and memorize these words so that they can inject them into conversations with their peers. The goal, of course, is to fool others into thinking that Mr. Word of the Day is more intelligent or better educated than everyone else. However, it doesn’t always pan out, as shown in this made up but entirely plausible example:

Mr. Jefferson: “So John, anything interesting happen lately?”
Mr. McStevens: “Well Earl, I spent yesterday at work, went to the gym to play some racquetball afterwards and somehow discombobulated my shoulder.”
Mr. Jefferson: “Sorry to hear that John. It sounds… painful. I hope you get that worked out.”

It is usually necessary to make sacrifices in an uncommon word’s dictionary meaning in order to wedge it into common, everyday dialogue. I’m always reminded of the movie Mary Poppins when this happens: for some reason, saying supercalifragilisticexpialidocious makes children feel more intelligent. In the same way, forcing big words into a trivial conversation makes small-minded adults feel like they are somehow superior to others.

Needless to say, I find the whole Word of the Day silliness to be most irritating, especially when something like this happens:

ruminant-ruminations-000000-formatted

Reading this after many consecutive hours of processing literal meanings from dense technical material in front of a computer screen really does something strange to a person’s brain, such as imagining sheep writing poetry in a field on a sunny day.

ruminant-ruminations-000001-formatted

Here is a summary of my drawn-out thought process after reading this not-so-carefully-composed Word of the Day definition:

A pen for sheep? That doesn’t sound right, but there it is. Maybe it’s possible. After all, the world is a really big place and has all kinds of interesting critters in it. Maybe they have intelligent sheep in the more remote areas of Europe..? But sheep that can write? No… that can’t possibly be correct. If sheep can write then certainly dogs can write, but I have never met a dog that can write. Wait a second… maybe the pen is a special name for a farm tool that maintains a sheep’s hooves? Okay, that might work. Do they ride sheep in Europe? Etc. Etc.

It took nearly five minutes for my brain to paint a mental image that was different than the illustration above, or one of an Icelander riding a saddled sheep into town for road supplies. Another 30 minutes passed before I remembered why I went to that damned dictionary website in the first place. When everything was said and done, I burned through almost 45 minutes of my day confirming to myself that sheep can’t write and trying to remember what the hell I was originally doing.

Cross Purposes

As I prepare to test for my Java certifications, I am frequently reminded that patience is not always a virtue. See below:

03. class Alpha {
04.   static String s = " ";
05.   protected Alpha() {
06.     s += "alpha ";
07.   }
08. }
09. class SubAlpha extends Alpha {
10.     private SubAlpha() {
11.       s += "sub ";
12.     }
13. }
14. public class SubSubAlpha extends Alpha {
15.    private SubSubAlpha() {
16.      s += "subsub ";
17.    }
18.    public static void main( String[] args ) {
19.      new SubSubAlpha();
20.      System.out.println( s );
21.    }
22. }

What is the result?
A.  subsub
B.  sub subsub
C.  alpha subsub
D.  alpha sub subsub
E.  Compilation fails
F.  An exception is thrown at runtime

Answer:  C is correct.  Watch out, because SubSubAlpha extends
Alpha!  Since the code doesn't attempt to make a SubAlpha, the
private constructor in SubAlpha is okay.

Yes, I must concede that I got this particular question wrong. And you know what? I’m not going to lose a bit of sleep over it. While I regularly use private constructors in my classes, I have yet to use them in tandem with any descendents of said classes. If I was willing (or perhaps able) to spend more than two or three minutes on the problem during the exam, the private constructor would have received additional scrutiny and led me along a path to the correct answer.

The point is this: I could have made the investment of an hour and I never would have noticed the SubSubAlpha extends Alpha bullshit, which serves as a nearly instantaneous escape hatch for the inexperienced and superficially intelligent. People who write obnubilated code and excel at these types of questions are the kind you want working for your competitors, not with you.

Contemplative Consternative Quandary

A person has two imaginary friends.

He talks about one to the other all the time, and vice versa.

After many months of this, both imaginary friends decide that they should be introduced.

The person keeps putting off this introduction, however, because he is afraid that one is going to find out the other is not real (and vice versa).