Clojure应用映射和关键字参数销毁 [英] Clojure applying a map and keyword arguments destruction
问题描述
考虑具有以下签名的函数:
Consider a function with the following signature:
(defn make-widget [& {:keys [x y] :or {x 10 y 20}}]
...)
将地图传递给函数的最佳方法是什么,例如:
What is the best way to pass a map to the function, e.g.:
(make-widget {:x 100})
或
(make-widget {:y 200 :x 0})
我目前想到的是通过vec
,flatten
和apply
例如:
What I have currently thought of is via vec
, flatten
and apply
e.g.:
(apply make-widget (flatten (vec ({:x 100}))
我坚信,有更好的方法可以做到这一点.你能考虑一个吗?
I strongly believe there is a better way to do this. Can you please consider one?
推荐答案
我也没有想到一种更优雅的方式,尽管在我看来应该有一种方式(例如apply
).
I can't think of a more elegant way, either, though it seems to me to that there should be one (like a map-specific variant of apply
).
使用flatten
会带来很多问题,但并不十分优雅.如果地图的值是集合,则flatten
也会在这些值上递归工作,因此事情可能会完全混淆.此替代方案避免了该问题:
Using flatten
has problems beyond not being very elegant, though. If the values of your map are collections, flatten
will work recursively on those, too, so things could get totally mixed up. This alternative avoids that problem:
(apply make-widget (apply concat {:x 100}))
这篇关于Clojure应用映射和关键字参数销毁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!