Sunday, July 19, 2015

Finished Chapter 4 of Clojure for the Brave and True

I have just finished the tasks at the end of Chapter 4 "Core Functions in Depth".
See my solutions below (hosted on github)
Some important lessons learned:
  1. When inserting into a sequence, make sure that the new sequence to insert is of the right type. Consider the following code:

    (into [{:name "Edward Cullen" :glitter-index 10} 
           {:name "Bella Swan" :glitter-index 0} 
           {:name "Charlie Swan" :glitter-index 0}]
       {:name "Mr Bean" :glitter-index 5})
    

    Result:

    [{:name "Edward Cullen", :glitter-index 10} 
       {:name "Bella Swan", :glitter-index 0} 
       {:name "Charlie Swan", :glitter-index 0}
       [:name "Mr Bean"] [:glitter-index 5]]
    

    Since in this case, the new sequence is a map, each key-value pair is treated as a new vector.
    The right way to insert a new map entry is the following:

    (into [{:name "Edward Cullen" :glitter-index 10} 
           {:name "Bella Swan" :glitter-index 0} 
           {:name "Charlie Swan" glitter-index 0}]
        [{:name "Mr Bean" :glitter-index 5}])
    

    Result:

    [{:name "Edward Cullen", :glitter-index 10}
     {:name "Bella Swan", :glitter-index 0} 
     {:name "Charlie Swan", :glitter-index 0}
     {:name "Mr Bean", :glitter-index 5}]
    


  2. and cannot be applied. There are some other ways to achieve the same result. One possible solution is the following:

       (apply = true '(true false true))
    

1 comment:

  1. After redoing the exercises, I managed to solve tocsv with a single function:

    (defn tocsv [suspects] (clojure.string/join \newline (map #(clojure.string/join "," [(:name %) (:glitter-index %)]) suspects)))

    ReplyDelete