Mark Mzyk | September 14, 2008

Today’s title is a play off of Stuart Halloway’s current series of blog posts titled Java.next. Stuart is focusing his series on the set of languages that run on the JVM and are looking to replace (or if not replace, then gain dominance alongside) Java.

In the third part of the series, Dispatch, Stuart writes about ways the Java.next languages dynamically choose behavior, one such way being with the switch statement. Stuart provides examples in Ruby (technically he should have used JRuby), Groovy, Clojure, and Scala. Stuart explores further than just the switch statement, but it was the switch statement example that caught my eye.

The example for each language is a simple piece of code that takes a grade (either numeric or letter) and returns the letter equivalent. If passed a 95, the code returns A. If passed 55, it returns F. If passed B, it returns B. If passed something that doesn’t equate to a valid grade, it throws an error.

I couldn’t resist coding it in Erlang.

Here is what I came up with:

-module(grades). -export([grades/1]). grades(N) -> case N of N when is_integer(N), N >= 90 -> "A"; N when is_integer(N), N >= 80 -> "B"; N when is_integer(N), N >= 70 -> "C"; N when is_integer(N), N >= 60 -> "D"; N when is_integer(N), N >= 0 -> "F"; "A" -> "A"; "a" -> "A"; "B" -> "B"; "b" -> "B"; "C" -> "C"; "c" -> "C"; "D" -> "D"; "d" -> "D"; "F" -> "F"; "f" -> "F"; N when true -> throw("Not a valid grade") end.

Now for the embarrassing admission: this code took me way longer to complete than it should have. I couldn’t remember the proper syntax for anything and I kept attempting to code Erlang like I was coding Python. I’m sure it’s not done the Erlang way and that I’ve missed someway to make it more compact. However, the code does work.

If you have a better solution, please submit it in the comments. If something can be improved, I always welcome knowing how.