Edit me

Basic syntax

Exercise 1: Compute 1 + 1

(+ 1 1)

Exercise 2: Call the function get with arguments "hello" and 1

(get "hello" 1)

Exercise 3: Compute (3 + 4 / 5) * 6

(* (+ 3 (/ 4 5)) 6)

Exercise 4: Define a vector with the elements 2, "nice" and true

[2 "nice" true]
# or
(vector 2 "nice" true)

Exercise 5: Define a vector that contains the keywords :key and :word

[:key :word]
# or
(vector :key :word)

Exercise 6: Define a map with the key :name associated with the value "Frederick"

{:name "Frederick"}
# or
(hash-map :name "Frederick")

Exercise 7: Use def to define a variable my-map that refers to the map {:1 2}. Use the put function to add a new key and value to my-map.

  • What does the put call return?
  • What is the value of my-map after the call?
(def my-map {:1 2})
(put my-map :3 4)
(def my-new-map (put my-map :5 6))

Exercise 8: Use push to add a value to a vector

(def my-vector [1 2])
(def new-vector (push my-vector 3))

Exercise 9: Use the function get to get the second element from a vector

(def my-vector [1 2])
(get my-vector 1)

Exercise 10: Use the function get to get the value of a key from a map

(def my-map {:k1 "v1" :k2 "v2"})
(get my-map :k2)

Exercise 11: Get the value of a key from a map using the map itself as a function

(def my-map {:k1 "v1" :k2 "v2"})
(my-map :k2)

Exercise 12: Get the value of a key from a map using a keyword as a function

(def my-map {:k1 "v1" :k2 "v2"})
(:k2 my-map)

Exercise 13: Use the function get-in to return the value :treasure from the map:

(def my-map {:description "cave"
            :crossroads [{:contents :monster}
                         {:contents [:trinket :treasure]}]})
(get-in my-map [:crossroads 2 :contents 1])

Exercise 14: Use defn to define a function hello that works like this: (hello) ==> "hello!"

(defn hello [] "hello!")

Exercise 15: Define a function double that works like this: (double 5) ==> 10

(defn double [n] (* n 2))

Exercise 16: Add a docstring to the function double. Then show it using (doc double)

(defn double
  "It doubles the received number."
  (* n 2))

Exercise 17: Implement a factorial function using recursion.

(defn factorial
  "Calculate the factorial number for n." 
  (if (<= n 1)
    (* n (factorial (dec n)))))