Clojure, lesson 1
Clojure is a functional language from the Lisp family that runs on the Java Virtual Machine. Its syntax is tiny, and it looks different from most languages at first. Here is the classic first program:
That line is a form: a list in parentheses. The first item is the function to call, and the
rest are its arguments. So (println "Hello, World!") means "call println with the string
"Hello, World!"". Where other languages write f(x, y), Clojure writes (f x y). Arguments
are separated by spaces; commas are allowed but treated as whitespace.
This rule has no exceptions, even for maths: (+ 1 2) is 3. It takes a day or two to get used
to, then it becomes very easy to read, because there is only one shape to remember.
println prints its arguments separated by spaces and then a new line:
2 exercises to try what you just read.
print does the same without the final new line, so the next print continues on the same line:
printf uses a format string with placeholders, like many other languages: %s for any
value as text, %d for whole numbers, %.2f for a number with two decimals. It does not add a
new line by itself, so end the format with %n:
A semicolon starts a comment that runs to the end of the line. By convention, ;; is used for a
comment on its own line and ; for one after code:
#_ in front of a form makes Clojure skip that whole form, which is handy for switching a piece
of code off: #_(println "skipped").
Clojure reads your file one form at a time, from top to bottom, and evaluates each form as soon as it has read it. If a form fails, you get an exception with a message and a stack trace; look for the first line that mentions your file and line number to find where it happened. Because Clojure starts a Java virtual machine first, even a tiny program takes about a second to run.
Write a program that prints exactly these two lines:
The program reads no input.
Print a short launch report. Build the first line from three print calls that print 3...,
2... and 1..., followed by (println "Liftoff!"). The second line uses one printf with a
%s and a %d placeholder to print the rocket name Comet and the crew size 4.
Expected output:
(println "Hello, World!")(println "Total:" 42) ; Total: 42
(println "a" "b" "c") ; a b c(print "Loading")
(print "...")
(println "done") ; Loading...done(printf "%s is %d years old%n" "Clojure" 19)
(printf "Pi is about %.2f%n" 3.14159) ; Pi is about 3.14;; This line is ignored.
(println "This runs") ; a note after codeHello, World!
I am learning Clojure.3...2...1...Liftoff!
Comet launched with 4 crew.