Define Functions in Clojure
Here are some different syntax options for defining functions in Clojure.
Most explicit to most implicit, longest to shortest. Repetition of the same function body.
Common: defn
The one you'll see the most is with the defn
keyword:
(defn is-published? [x]
(not= "true" (:draft x))
Shorter, Nested: fn
Next choice: Use fn. Shorter. Can be anonymous. Can define and bind within a let
expression within defn
.
Function signature:
(fn name? [params*] exprs*)
Used in let
:
(let [is-published? (fn [x] (not= "true" (:draft x)))])
Fun fact: defn
is actually a macro for:
(def is-published?
(fn [x] (not= "true" (:draft x)))
Anonymous: #
No outer parens. No name, ever. No named params:
(let is-published? #(not= "true" (:draft %)))