(fn [f & args] (apply f args)) 的标准版本或惯用用法 [英] Standard version or idiomatic use of (fn [f & args] (apply f args))

查看:12
本文介绍了(fn [f & args] (apply f args)) 的标准版本或惯用用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常发现自己想要在几个参数集合上应用一个函数集合.使用 map 和一个非常简单的函数很容易做到.

Every so often I find myself wanting to apply a collection of functions on several collections of parameters. It's easy to do with map and a very simple function.

(map
  (fn invoke [f & args] (apply f args))
  [- + *]
  [1 2 3]
  [1 2 3]
  [1 2 3])

 (-1 6 27)

在网络上搜索会发现很多定义类似函数的库,通常称为 funcall 或 invoke.由于 Clojure 对可变参数函数的偏爱,我不禁认为应该已经有这个函数的默认版本了.

Searching the web turns up quite a few libraries that define a similar function, often called funcall or invoke. Because of Clojure's penchant for variadic functions, I cannot help but think there should already be a default version of this function.

是否有,或者是否有另一种惯用的方法来解决这种情况?

Is there, or is there another idiomatic way to solve situations like this ?

另一种形式可能是

(map
  (comp eval list)
  [- + *]
  [1 2 3]
  [1 2 3]
  [1 2 3])

 (-1 6 27)

这让我害怕,因为 eval.

Which scares me because of the eval.

推荐答案

标准 Clojure 库中没有 funcall 或等效函数以这种方式工作."apply" 非常接近,但需要在最后收集参数而不是纯粹的可变参数.

There isn't a funcall or equivalent function in the standard Clojure library that works exactly this way. "apply" is pretty close but needs a collection of arguments at the end rather than being purely variadic.

考虑到这一点,您可以使用 apply 来欺骗",通过在末尾添加一个无限的 nil 列表(它们被视为附加参数的空序列)来使其工作如下:

With this in mind, you can "cheat" with apply to make it work as follows by adding an infinite list of nils to the end (which get considered as empty sequences of additional arguments):

(map apply [- + *] [1 2 3] [1 2 3] [1 2 3] (repeat nil))
=> (-1 6 27)

总的来说,如果你真的想经常使用这个函数,我认为明智的做法是定义它:

Overall though, I think the sensible approach if you really want to use this function frequently is just to define it:

(defn funcall [f & ps]
  (apply f ps))

(map funcall [- + *] [1 2 3] [1 2 3] [1 2 3])
=> (-1 6 27)

这篇关于(fn [f & args] (apply f args)) 的标准版本或惯用用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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