On 2/22/15 12:52 PM, Timur wrote:
Hi everyone,

I have the following question regarding the defmultis of clojure:

(defmulti create-fact
   (fn [item-vector] (do
                       (print item-vector)
                       (first item-vector))))

(defmethod create-fact [:a] [item-vector]
   (str "a"))

(defmethod create-fact [[:a "safs"]] [item-vector]
   (str "safs"))


(mapv create-fact {:a "safs"})


Dispatch function is not called in this case and return is "safs" so the
matching key is [[:a "safs"]]. I except it to be :a, why is that [[:a
"safs"]]?

First, observe:

> (seq {:a 1 :b 2})
([:a 1] [:b 2])

A map is converted into a sequence with each element being a key/value pair. The mapv function does this under the hood so that it can operate on the map as a sequence.

Now, when I run your code, I get an IllegalArgumentException stating that :a is not a dispatch value. This is correct, because the two dispatch values defined are [:a] and [[:a "safs"]]. If you change the [:a] method to be :a, then the return value will be "a". The dispatch values in each defmethod must be literal, and not wrapped in a vector like when defining the arguments to a fn.

Does that clear things up?

--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
--- You received this message because you are subscribed to the Google Groups "Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to clojure+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to