将映射应用于函数的其余参数

编程入门 行业动态 更新时间:2024-10-18 22:26:53
本文介绍了将映射应用于函数的其余参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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:关键词]

本文发布于:2023-03-27 08:08:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/686666.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:应用于   函数   参数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!