On Nov 26, 7:42 am, Stefan Rohlfing <stefan.rohlf...@gmail.com> wrote:
> 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?

It has the effect that calling (merge-with f nil), or (merge-with f
nil nil nil), returns nil rather than an empty map. I guess that's the
reason for it.

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

Calling seq on a map returns a sequence of Map$Entry objects (which
look a lot like two-element vectors, but are not quite the same).
first calls seq.

- Chris

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