Fork me on GitHub
#beginners
<
2017-03-05
>
zea04:03:42

Hi there! Anyone care to explain, the differences between list, vector, and map? And when to use them? Thank you so much! :)

seancorfield06:03:37

And if you want to understand more under the hood http://insideclojure.org/2016/03/16/collections/

kauko09:03:54

@zea list and vector are for storing individual things in order. Map is for storing key-value pairs. Maps are not ordered, unless you specifically use an ordered map (usually no need for this). For example, if you want to represent a person, you'd use a map {:name "zea" :id 1}

kauko09:03:49

(def chat-members [{:name "zea} {:name "kauko"}])

zea09:03:09

@kauko so what is the difference between list and vector then? I get the idea of map thou, thanks! @seancorfield thanks for the reference sir!

kauko09:03:58

Mmmh, I guess for now you only need to know that lists and vectors can behave differently when for example you conj stuff into them.

cljs.user=> (conj `(1 2 3) 4)
(4 1 2 3)
cljs.user=> (conj [1 2 3] 4)
[1 2 3 4]
cljs.user=>
`

kauko09:03:58

There may be situations when you should use one over the other, but usually those are perfomance related, which means you don't really need to worry about it you're just learning IMO 🙂

curlyfry09:03:49

@zea Have you looked at Clojure for the Brave and True? It's a pretty great introduction to the language!

jeffh-fp15:03:03

hey I seem to be having an arity problem with multimethods...

(defmulti cast-spell (fn [mage] (:mage-type mage)))

(defmethod cast-spell :summoner
  [mage victim]
  (str "Summoner mage " (:name mage) " casts a spell on " (:name victim)))

(cast-spell {:mage-type :summoner
             :name "Archdeacon Gotham"}
            {:name "Poor Victim"})
Results in: ArityException Wrong number of args (2) passed to: user/eval10235/fn--10236 clojure.lang.AFn.throwArity (AFn.java:429)

jeffh-fp15:03:33

if I take out the victim references in the defmethod (and the 2nd map in the call to cast-spell it works fine ...

jeffh-fp15:03:14

I found some suggestions that this might be due to redefinition of the multimethod but it's the same when I do it in a clean REPL

jeffh-fp15:03:51

ok I guess it just takes posting the question to finally figure it out... I changed the arity of the defmulti to match and it works now. I thought for sure I had tried that before but maybe not in a clean REPL

jeffh-fp15:03:08

(defmulti cast-spell (fn [mage victim] (:mage-type mage))) ...

seancorfield21:03:40

@zea vector is indexed — so random access is O(1) — list is sequential so accessing the nth element is O(n) /cc @kauko