问题描述
在Clojure中,如果我有一个函数f,
In Clojure, if I have a function f,
(defn f [& r] ... )
并且我有一个 seq args 带有我想调用 f 的参数,我可以轻松地使用 apply:
and I have a seq args with the arguments I want to call f with, I can easily use apply:
(apply f args)
现在,假设我有另一个函数 g,它被设计为采用许多可选的命名参数中的任何一个 - 也就是说,其余参数被解构为映射:
Now, say I have another function g, which is designed to take any of a number of optional, named arguments - that is, where the rest argument is destructured as a map:
(defn g [& {:keys [a b] :as m}] ... )
我通常会通过做类似的事情来调用 g
I'd normally call g by doing something like
(g :a 1 :b 2)
但是如果我碰巧有一个值为 {:a 1 :b 2} 的地图 my-map,并且我想将 g应用"到我的地图 - 换句话说,得到一些最终会作为上述调用的东西,那么我自然不能使用apply,因为它相当于
but if I happen to have a map my-map with the value {:a 1 :b 2}, and I want to "apply" g to my-map - in other words, get something that would end up as the above call, then I naturally couldn't use apply, since it would be equivalent to
(g [:a 1] [:b 2])
有什么好的方法可以解决这个问题吗?我可能会在我的设计中偏离轨道以结束这个吗?我能找到的最佳解决方案是
Is there a nice way to handle this? May I have gone off track in my design to end up with this? The best solution I can find would be
(apply g (flatten (seq my-map)))
但我肯定不喜欢它.有什么更好的解决方案吗?
but I surely don't like it. Any better solutions?
对建议的解决方案的轻微改进可能是
A slight improvement to the suggested solution might be
(apply g (mapcat seq my-map))
这至少删除了一个函数调用,但可能仍然不是很清楚发生了什么.
which at least removes one function call, but it may still not be very clear what's going on.
推荐答案
我自己偶然发现了这个问题,最终定义了期望一张地图的函数.一个映射可以有可变数量的键/值对,如果足够灵活,那么就不需要 &休息论据.申请也没有痛苦.让生活更轻松!
I have stumbled into this problem myself and ended up defining functions to expect one map. A map can have a variable amount of key/value pairs, and if flexible enough, so there is no need for & rest arguments. Also there is no pain with apply. Makes life a lot easier!
(defn g [{:keys [a b] :as m}] ... )
这篇关于将映射应用于函数的其余参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论