In this installment of “Functional programming without feeling stupid” I would like to show you how to define things in Clojure. Values and function applications are all well and good, but if we can’t give them symbolic names, we need to keep repeating them over and over.
Before we start naming things, let’s have a look at how Clojure integrates with Java. I’m assuming you are still in the REPL, or have started it again with
Track 1: “If anyone should ask / We are mated”
As it happens, Clojure’s core library is lean and focused on manipulating the data structures of the language, so many things are deferred to the underlying Java machinery as a rule. For example, mathematical computation is typically done using the static methods in the
user=> (java.lang.Math/sqrt 5.0) 2.23606797749979
As you can see, this is a function application like we have already seen in Part 1, but this time the function we are using is the
sqrt static method in the
Java 7 acquired Unicode character names, and they are accessed through
getName method in the
java.lang.Character class. This is no mean feat, since there are over 110,000 characters in the Unicode standard, and each of them has a name (although some of them are algorithmically generated). To find out the canonical character name of a Unicode character, such as the euro currency symbol, you would use the
getName static method:
user=> (java.lang.Character/getName \u20ac) ClassCastException java.lang.Character cannot be cast to java.lang.Number user/eval703 (NO_SOURCE_FILE:1)
Hey, what’s wrong? Well, if you look up the documentation of
java.lang.Character.getName, you will find out that it takes an
int value as an argument, not a character. You can actually do this check from inside the REPL:
user=> (javadoc java.lang.Character) true
The REPL doesn’t seem to do much, but you should now have a new web browser window or tab open, with the JavaDoc of the java.lang.Character class loaded up. That’s what the REPL meant when it said
Javadoc: (javadoc java-object-or-class-here)
when it started up. The
getName method does need an
int value, so let’s try something else:
user=> (java.lang.Character/getName (int \u20ac)) "EURO SIGN"
All right! How about another one:
user=> (java.lang.Character/getName 67) "LATIN CAPITAL LETTER C"
Well, some say that Clojure is the new C.