Dear Clojure Group,

Today I took a closer look at the 'merge-with' function of Clojure
Core and changed some parts to better understand its implementation.

Now I still have two questions regarding the following code:


(defn my-merge-with [f & maps]
  (when (some identity
maps)                                                ;; question 1
    (reduce (fn [acc m]
                     (let [key (key (first  m)) val (val (first
m))]          ;; question 2
                       (assoc acc key (if-let [old-val (get acc key)]
                                                     (f old-val val)
                                                      val))))
     {} maps)))



 (my-merge-with + {"t" 1} {"a" 1} {"c" 1} {"g" 1} {"g" 1} {"g" 1} {"a"
1} {"c" 1} )
;; {"g" 3, "c" 2, "a" 2, "t" 1}

Question 1:
(when (some identity maps)

This expression from the original implementation checks if the
provided coll is empty.
However, why not just use (when (empty? maps) or (when (seq maps)
instead?

Question 2:
In order to return the key of a map consisting of one key/value pair I
have to use the 'first' function, otherwise an exception will be
thrown:

(key {:a "a"})
;; clojure.lang.PersistentArrayMap cannot be cast to java.util.Map
$Entry
;;  [Thrown class java.lang.ClassCastException]

(key (first {:a "a"}))
;; :a

I understand that 'key' expects a java.util.Map$Entry object, but how
exactly does using 'first' accomplish this?

(first {:a "a"})
;; [:a "a"]

[:a "a"] is not a vector because the 'key' function does not work on a
vector:

(key [:a "a"])
;; clojure.lang.PersistentVector cannot be cast to java.util.Map$Entry
;;   [Thrown class java.lang.ClassCastException]

Any suggestions are very welcome!

Stefan

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

Reply via email to