在Clojure中将对象包装到集合中的惯用方式(如果还不是集合)? [英] Idiomatic way to wrap object into collection (if it's not a collection already) in Clojure?
问题描述
例如,我有多种数据结构,例如 {:name"Peter":children"Mark"}
和 {:name"Mark":children ["Julia" John]
即:children的值可以是单个字符串或字符串集合.我代码中的其他函数期望:children的值始终是字符串的集合,因此我需要为其修改数据.
当然,我可以使用类似的东西:
I have (for instance) a mix of data structures such as {:name "Peter" :children "Mark"}
and {:name "Mark" :children ["Julia" "John"]
i.e. :children value is either a single string or a collection of strings. Other functions in my code expect that the value of :children is always a collection of strings, so I need to adapt the data for them.
Of course I can use something like:
(defn data-adapter [m]
(let [children (:children m)]
(assoc m :children
(if (coll? children)
children
[children]))))
但是还有一种惯用/简洁的方法吗?
But is there a more idiomatic/laconic way?
推荐答案
我认为您不必回答.
(if(coll?x)x [x])
尽可能简洁明了.这就是人们通常用来解决此问题的方式(有时使用 sequential?
而不是 coll?
).
(if (coll? x) x [x])
is about as terse and expressive as it gets. It’s what people usually use for this problem (sometimes with sequential?
instead of coll?
).
cond->
爱好者有时会尝试使用它来代替一个简单的条件,但是在这里并没有改善:
cond->
enthusiasts like me sometimes try to use it in place of a simple conditional, but here it is no improvement:
(cond-> x (not (coll? x)) vector)
但是,在代码的上下文中,您可以做得更好.查找和关联最好用 update
:
In the context of your code, however, you can do a little better. A lookup and association is best expressed with update
:
(defn data-adapter [m]
(update m :children #(if (coll? %) % [%])))
这篇关于在Clojure中将对象包装到集合中的惯用方式(如果还不是集合)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!