You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按规则将Clojure向量转换为映射?

问题:将交错结构的Clojure向量转换为映射

我是Clojure新手,需要把交错结构的向量转换成映射,转换规则如下:

  • 向量中的关键字若后续是关键字,则该关键字对应值为true;
  • 若后续是非关键字、非映射类型的值,则该关键字对应此值。

示例

输入向量:
[:enchant :type "Fire Aspect" :level 123]
期望转换结果:
{:enchant true :type "Fire Aspect" :level 123}

最终解决代码

(defn parse-args
  ([args]
   (parse-args args {}))
  ([[fst sec & more] rst]
   (let [value? (fn [x] (and (not (keyword? x))
                             (not (map? x))))]
     (cond
       (and (keyword? fst)
            (keyword? sec)) (parse-args (cons sec more) (merge rst {fst true}))
       (and (keyword? fst)
            (value? sec)) (parse-args more (merge rst {fst sec}))
       :else rst
       ))))

最初尝试的笨拙实现

一开始我尝试的方法比较复杂且笨拙,很快发现这种思路走不通:

(defn parse-arg [args toggle-coll]
  (let [is-value? #(not (and (keyword? %)
                             (map? %1)))]
    (reduce (fn [k1 k2]
              (merge
                (cond
                  (and (keyword? k1)
                       (keyword? k2)) ({} {k1 true})
                  (and (keyword? k1)
                       (is-value? k2)) ({} {}) ; 很快发现这种方法复杂又笨拙
                  (and (map? k1)
                       (is-value? k2)) ({} {})
                  (and (map? k1)
                       (keyword? k2)) ({} {})
                  ;; 后续代码已省略
                )
              )
            args)))

内容的提问来源于stack exchange,提问作者Freeze Dolphin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 19:32:48