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

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

问题描述

我经常发现自己想要对几个参数集合应用一组函数。它很容易做map和一个非常简单的函数。

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

(-1 6 27)

搜索web会出现一些库,函数,通常称为funcall或invoke。因为Clojure喜欢可变函数,我不禁想到应该已经有一个默认版本的这个函数。



有没有,还是有另一个惯用的方法来解决



另一种形式可能是

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

(-1 6 27)

这是因为eval会吓到我。

解决方案

funcall 或在标准Clojure库中的等效函数,其工作方式完全相同。 apply非常接近,但在结尾处需要一个参数集合,而不是纯可变的。



考虑到这一点,你可以它通过添加一个无限的nils列表到最后(它被认为是额外的参数的空序列)工作如下:

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

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

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

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


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)

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 ?

Edit:

Another form may be

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

 (-1 6 27)

Which scares me because of the eval.

解决方案

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.

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天全站免登陆