We’ll see how long this lasts, but I think I’m going to start posting tiny posts that cover a little bit of clojure here and there in order to help me learn it.
I’ve already read a few clojure books, and done some tutorials online (such as the awesome clojure koans and modern cljs) but I still don’t feel like I really know clojure. I’m hoping that writing out examples and playing with tiny bits of the language every day will help fix that.
Since clojure is a lisp, when you’re calling a function it always takes the form of (function-name arg1 arg2 ...)
. Everything is contained within the parenthesis.
Very important– the last value/function result is always what is returned from a function.
There is no return type of void
in clojure. A function that returns nothing actually returns nil
.
One creates functions via defn
. Note that to make a comment in code, you begin it with two semicolons ;;
.
Notice that even the function to define a function follows the lisp rules.
Interestingly there’s a built in format for documentation– I could’ve written the above function like so:
I don’t know of another language that has that feature off hand– I like it.
This is one of the strangest part of clojure functions for me– the same function definition can have multiple aritys. (What’s the plural of arity?..) This means that you can define a different number of parameters with their own function bodies in the same function definition.
To demonstrate, we’ll make a new function say-hello2
that accepts either a whole name or a first name and last name.
I think in the next installment we’ll look at anonymous functions… we’ll see.