Clojure Functions
; Use fn to create new functions. A funtion always returns its last statement.
(fn [] “Hello World”) ; => fn
; (You need extra parens to call it)
((fn [] “Hello World”)) ; => “Hello World”
; You can create a var using def
(def x 1)
x ; => 1
; Assign a function to a var
(def hello-world (fn [] “Hello World”))
(hello-world) ; => “Hello World”)
; You can shorten this process by using defn
(defn hello-world [] “Hellow World”)
; The [] is the list of arguments for the function.
(den hello [name]
(str) “Hello ” name))
(hello “Steve”) ; => “Hello Steve”
; You can also use this shorthand to create functions:
(def hello2 #(str “Hello “ %1))
(hello2 “Fanny”) ; => “Hello Fanny”
; You can have multi-variadic functions, too
(defn hello3
([] “Hello World”)
([name] (str “Hello “ name))
(hello3 “Jake”) ; => “Hello Jake”
(hello3) ; => “Hello World”
; Functions can packextra arguments up in a seq for you
(defn hello-count [name & args]
(str “Hellow “ name “, you passed “ (count args) “ extra args”))
(hello-count “Jamie” 1 2 3 4 5)
; => "Hello Jamie, you passed 5 extra args"