gpt4 book ai didi

clojure - 如何有条件地连接到 clojure 向量

转载 作者:行者123 更新时间:2023-12-03 02:05:40 26 4
gpt4 key购买 nike

是否有更简洁的方法可以在 clojure 中执行以下操作?

(defn this [x] (* 2 x))
(defn that [x] (inc x))
(defn the-other [x] (-> x this that))

(defn make-vector [thing]
(let [base (vector (this (:a thing))
(that (:b thing)))]
(if-let [optional (:c thing)]
(conj base (the-other optional))
base)))

(make-vector {:a 1, :b 2}) ;=> [2 3]
(make-vector {:a 1, :b 2, :c 3}) ;=> [2 3 7]

我所说的“更清洁”是指更接近这个的东西:

(defn non-working-make-vector [thing]
(vector (this (:a thing))
(that (:b thing))
(if (:c thing) (the-other (:c thing)))))

(non-working-make-vector {:a 1, :b 2} ;=> [2 3 nil] no nil, please!
(non-working-make-vector {:a 1, :b 2, :c 3} ;=> [2 3 7]

请注意,我可能想在任意键上调用一些任意函数(例如 thisthatthe-other) thing 并将结果放入返回的向量中。重要的是,如果映射中不存在该键,则不应在向量中放置 nil

这类似于 this question但输出是矢量而不是 map ,因此我无法使用merge

最佳答案

(defn this [x] (* 2 x))
(defn that [x] (inc x))
(defn the-other [x] (-> x this that))

(def k-f-map {:a this
:b that
:c the-other})

(def m1 {:a 1 :b 2})
(def m2 {:a 1 :b 2 :c 3})

(defn make-vector [k-f-map m]
(reduce (fn [res [fk fv]]
(if (fk m)
(conj res (fv (fk m)))
res))
[] k-f-map))

(make-vector k-f-map m1)
-> [2 3]

(make-vector k-f-map m2)
-> [2 3 7]

关于clojure - 如何有条件地连接到 clojure 向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13888290/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com