Skip to content

Instantly share code, notes, and snippets.

; square the numbers 0 to 4 using map
user=> (map #(* % %) (range 5))
(0 1 4 9 16)
; concatenate strings with a space using reduce
user=> (reduce (fn [acc x] (str acc " " x)) '("hello" "world"))
"hello world"
; sum the numbers in a list
user=> (reduce + [1 2 3 4 5])
15
; reflectively apply arguments to a function to check if a list is sorted
; defining a function to square a number
user=> (defn square [x] (* x x))
#'user/square
user=> (square 3)
9
; now using an anonymous function
user=> (def square2 (fn [x] (* x x)))
#'user/square2
user=> (square2 3)
; First let's show two alternative ways to destructure a vector
user=> (defn first-three [a & [b & [c]]] (println a b c))
#'user/first-three
user=> (defn first-three [a b c & _] (println a b c))
#'user/first-three
user=> (first-three 1 2 3 4)
1 2 3
nil
user=> (first-three 1 2)
1 2 nil
; Trying to pattern match on the list parameter
user=> (defn my-count "Count number of items"
#_=> ([[]] 0)
#_=> ([[x & rest]] (+ 1 (my-count rest))))
CompilerException java.lang.RuntimeException: Can't have 2 overloads with same arity, compiling:(NO_SOURCE_PATH:1)
; What we have to do instead...
user=> (defn my-count "Count number of items"
#_=> ([xs] (if (empty? xs)
#_=> 0
#_=> (+ 1 (my-count (rest xs))))))
; Let's create a function of varying arity
user=> (defn sum "Naive parameter summation"
#_=> ([x] x)
#_=> ([x & xs] (+ x (apply sum xs)))) ; We use apply to reflectively call the function
#'user/sum
user=> (sum 1)
1
user=> (sum 1 2)
3
user=> (sum 1 2 3)
; Defining functions the long way using def
user=> (def add "Adds two numbers, x and y" (fn [x y] (+ x y)))
#'user/add
user=> (add 1 2)
3
; Defining functions the short way
user=> (defn add "Adds two numbers, x and y" [x y] (+ x y))
user=> (add 1 2)
3
; Viewing the documentation
; Creating maps
user=> {:one 1, :two 2 :three 3} ; Note: commas are treated as whitespace
{:one 1, :three 3, :two 2}
user=> (hash-map :one 1, :two 2)
{:one 1, :two 2}
; Accessing and using maps
user=> (def nums {:one 1, :two 2, :three 3}) ; Note: we introduce def to define/bind a variable
#'user/nums
user=> (nums :one)
1
; Creating sets
user=> #{:a :b :c 1 2 3}
#{1 2 3 :a :c :b}
user=> (class #{})
clojure.lang.PersistentHashSet
user=> (hash-set :a :b :c 1 2 3)
#{1 2 3 :a :c :b}
user=> (sorted-set :c :b :a)
#{:a :b :c}
user=> (set '(1 2 3 1 2 3))
; Creating vectors
user=> [:a :b :c]
[:a :b :c]
; Operating on vectors
user=> (first [:a :b :c])
:a
user=> (nth [:a :b :c] 2) ; NOTE: 0-based index
:c
user=> ([:a :b :c] 2)
:c
user=> (1 2 3) ; interpreted as function form (1 is trying to be called as a function)
ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn user/eval343 (NO_SOURCE_FILE:1)
; so we either use the clojure.core/list function or the '() macro
user=> (list 1 2 3)
(1 2 3)
user=> '(1 2 3)
(1 2 3)
; here are some functions that can be performed on lists
user=> (first '(1 2 3))
1