如何将矢量映射到地图,将重复键值推入其中?

Ped*_*lva 3 vector clojure hashmap

这是我的输入数据:

[[:a 1 2] [:a 3 4] [:a 5 6] [:b \a \b] [:b \c \d] [:b \e \f]]
Run Code Online (Sandbox Code Playgroud)

我想将此映射到以下内容:

{:a [[1 2] [3 4] [5 6]] :b [[\a \b] [\c \d] [\e \f]]}
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止:

(defn- build-annotation-map [annotation & m]
 (let [gff (first annotation)
       remaining (rest annotation)
       seqname (first gff)
       current {seqname [(nth gff 3) (nth gff 4)]}]
   (if (not (seq remaining))
     m
     (let [new-m (merge-maps current m)]
       (apply build-annotation-map remaining new-m)))))

(defn- merge-maps [m & ms]
  (apply merge-with conj
         (when (first ms)                                                                                                              
           (reduce conj                     ;this is to avoid [1 2 [3 4 ... etc.                                                                                                          
                   (map (fn [k] {k []}) (keys m))))                                                                                    
         m ms))
Run Code Online (Sandbox Code Playgroud)

以上产生:

{:a [[1 2] [[3 4] [5 6]]] :b [[\a \b] [[\c \d] [\e \f]]]}
Run Code Online (Sandbox Code Playgroud)

我觉得这个问题很明显merge-maps,特别是传递给merge-with(conj)的函数,但是在我敲了一会儿之后,我已经准备好帮助我了.

我一般都是lisp的新手,特别是clojure,所以我也很欣赏那些没有专门针对这个问题的评论,还有我的风格,脑死亡构造等等.谢谢!

解决方案(无论如何,足够接近):

(group-by first [[:a 1 2] [:a 3 4] [:a 5 6] [:b \a \b] [:b \c \d] [:b \e \f]])
=> {:a [[:a 1 2] [:a 3 4] [:a 5 6]], :b [[:b \a \b] [:b \c \d] [:b \e \f]]}
Run Code Online (Sandbox Code Playgroud)

May*_*iel 9

(defn build-annotations [coll]
  (reduce (fn [m [k & vs]]
            (assoc m k (conj (m k []) (vec vs))))
          {} coll))
Run Code Online (Sandbox Code Playgroud)

关于您的代码,最重要的问题是命名.首先,我不会,尤其是如果不了解你的代码,有什么想法,什么叫annotation,gffseqname.current也很模糊.在Clojure中,remaining通常会more根据上下文调用,以及是否应使用更具体的名称.

在你的let语句中gff (first annotation) remaining (rest annotation),我可能会利用解构,如下所示:

(let [[first & more] annotation] ...)

如果您更愿意使用,(rest annotation)那么我建议使用next,因为nil如果它是空的,它将返回,并允许您写(if-not remaining ...)而不是(if-not (seq remaining) ...).

user> (next [])
nil
user> (rest [])
()
Run Code Online (Sandbox Code Playgroud)

在Clojure中,与其他lisps不同,空列表是真实的.

本文介绍了惯用命名的标准.