将映射应用于函数的rest参数 [英] Applying a map to a function's rest argument

查看:92
本文介绍了将映射应用于函数的rest参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Clojure中,如果我有函数 f

In Clojure, if I have a function f,

(defn f [& r] ... )

我有一个序列 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)

,但是如果我碰巧有一张地图{i> my-map ,其值为{:a 1:b 2},并且我想将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}] ... )

这篇关于将映射应用于函数的rest参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆