为什么我应该在Clojure中使用'apply'? [英] Why should I use 'apply' in Clojure?

查看:101
本文介绍了为什么我应该在Clojure中使用'apply'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Rich Hickey在其中一篇博文中说的,但我不明白使用apply的动机。请帮助。

This is what Rich Hickey said in one of the blog posts but I don't understand the motivation in using apply. Please help.


Clojure和CL之间的一个巨大区别是Clojure是一个Lisp-1,所以funcall不需要,只用于将一个函数应用于运行时定义的参数集合。因此,(apply f [i])可以写成(fi)。

A big difference between Clojure and CL is that Clojure is a Lisp-1, so funcall is not needed, and apply is only used to apply a function to a runtime-defined collection of arguments. So, (apply f [i]) can be written (f i).

-1和funcall不需要?我从未在CL中编程。

Also, what does he mean by "Clojure is Lisp-1" and funcall is not needed? I have never programmed in CL.

感谢

推荐答案

如果传递给函数的参数数量在编译时未知 ,请使用 apply (对不起,不知道Clojure语法, ):

You would use apply, if the number of arguments to pass to the function is not known at compile-time (sorry, don't know Clojure syntax all that well, resorting to Scheme):

(define (call-other-1 func arg) (func arg))
(define (call-other-2 func arg1 arg2) (func arg1 arg2))

在编译时是已知的,您可以直接传递它们,就像上面的例子。但是如果参数的数量在编译期是未知的,你不能这样做(好吧,你可以尝试这样):

As long as the number of arguments is known at compile time, you can pass them directly as is done in the example above. But if the number of arguments is not known at compile-time, you cannot do this (well, you could try something like):

(define (call-other-n func . args)
   (case (length args)
      ((0) (other))
      ((1) (other (car args)))
      ((2) (other (car args) (cadr args)))
      ...))

但这会成为一个噩梦很快。这是应用输入图片的地方:

but that becomes a nightmare soon enough. That's where apply enters the picture:

(define (call-other-n func . args)
   (apply other args))

它包含任何数量的参数作为它的最后一个参数,并调用作为第一个参数传递给 apply 的函数。

It takes whatever number of arguments are contained in the list given as last argument to it, and calls the function passed as first argument to apply with those values.

这篇关于为什么我应该在Clojure中使用'apply'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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