Basic syntax

Question 1: Compute 1 + 1

(+ 1 1)

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

(get "hello" 1)

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

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

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

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

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

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

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

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

Question 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))

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

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

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

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

Question 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)

Question 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)

Question 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)

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

{:description "cave"
:crossroads [{:contents :monster}
             nil
             {:contents [:trinket :treasure]}]}

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

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

(defn hello [] "hello!")

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

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

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

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

Question 17: Implement a factorial function using recursion

(defn factorial [n]
  (if (<= n 1)
  n
  (* n (factorial (dec n)))))