Clojure is a programming language that is a lisp. You can use the REPL on http://app.klipse.tech to try out the examples.
A clojure function has this form:
(defn <function-name> [<arg-list>]
body)
For example, here's an increment function:
(defn increment [a]
(+ a 1))
(increment 6) ;; returns 7
(defn sum [a b]
(+ a b))
(sum 40 2) ;; returns 42
You can also have an anonymous function (a function without a name!):
(fn [a b] (- a b))
;; returns a - b
As you've seen earlier, you can call a function like so:
(increment 3) ;; returns 4
(sum 3 4) ;; returns 7
((fn [a b] (- a b)) 4 3) ;; returns 1
Note that in clojure we use prefix notation for calling functions.
Here are some common functions used in clojure:
map
is used to iterate over sequences, like vectors (arrays are called vectors in Clojure).
A map
takes a function and applies it to each of the elements in the sequence:
(map increment [1 2 3 4 5])
;; returns [2 3 4 5 6]
(map (fn [element] (sum element 5) [1 2 3])
;; returns [6 7 8]
A filter
runs a function on every element of a sequence and keeps that element if the function returns true.
(filter (fn [v] (= v 2)) [1 2 3 2 4]) ;; returns [2 2]
reduce
is another commonly used function that performs an aggregation, or "reduction" over a sequence. It takes a function, an initial value, and a sequence as input. Often the result is a single value. You can read more about it here: https://clojuredocs.org/clojure.core/reduce. Here are a couple of examples:
(+ 1 2) ;; returns 3
(reduce + 0 [1 2 3 4 5]) ;; returns 15
(reduce + 10 [1 2 3 4 5] ;; returns 25