Wednesday 29 June 2011

Hello World in Clojure

For the first script in Clojure naturally we want to see Hello World.  In this case the script checks to see whether there are any command line arguments: this is passed in to the script via the global identifier *command-line-args*. If not, it writes Hello World to the standard output: if there are arguments it takes the first item and uses that in its greeting.

I don't think there is an explicit entry point in a Clojure program: the interpreter just starts running the first runnable code it finds.

The namespace directive at the top reflects the path to the script: in a file helloworld.clj which is in a folder examples which is in a folder that is in the classpath passed to Clojure by the script that calls the interpreter.

So we run the script from the folder c:\Users\phancock\Documents\Clojure as follows:-


>clojure examples/helloworld.clj
Hello World
>clojure examples/helloworld.clj Polly
Hello Polly


ok.  So this is the script:-


(ns examples.helloworld)
(if (empty? *command-line-args*)
    (println "Hello World")
    (println "Hello" (first *command-line-args*)))


The hard part is just getting the choreography of paths and class paths and namespaces clear in my mind. This is the bit that the books skim over to get to the easy stuff, writing the code. "With these mechanical details mastered, everything else is comparatively easy" (Kernighan & Ritchie p.6)

No comments:

Post a Comment