问题描述
对我来说 apply
是Clojure中更难的函数之一。我正在寻找一个很好的定义,它的力学 - 它是什么,特别是关于它如何抓住的参数,它馈送到作为第一个参数提供的函数。例如这个定义:
To me apply
is one of the more difficult functions in Clojure. I'm looking for a good definition of its mechanics - what exactly it does, especially regarding how it 'grabs' arguments that it feeds to the function it is supplied as the first parameter. For instance this definition:
深入/#applyrel =nofollow>图书。有比它更多吗?在我看来, apply
可以给出许多自由参数(参数不在任何数据结构中),并将它们提供给给定的函数。如何应用
的规则是什么?grabs params的功能?是什么让它停止?
, from the 'Brave and True' book. Is there more to it than that? It seems to me that apply
can be given many 'free' arguments (arguments not in any data structure) and will supply them to the given function. What are the rules for how apply
grabs params for its function? What makes it stop?
推荐答案
apply
因此,例如:
(apply f 1 2 [3 4] 5 [6 7 8])
相当于:
(apply f (concat [1 2 [3 4] 5] [6 7 8]))
我在这一步中所做的每一个参数,除了最后一个,并把它们放入一个序列(这里我使用了一个向量,但确切的类型没有关系),然后连接该序列
All I've done in this step is take every argument except the last one and put them into a sequence (here I've used a vector, but the exact type doesn't matter), then concatenated that sequence with the last argument (which was already a sequence).
进一步,我们得到这个:
Simplying further, we get this:
(apply f [1 2 [3 4] 5 6 7 8])
这相当于:
(f 1 2 [3 4] 5 6 7 8)
为了更好地理解 apply
的行为,它像这样工作:
To better understand the behavior of apply
, you can think of it as working like this:
(defn apply [f & args]
(.applyTo f (seq (lazy-cat (drop-last args) (last args)))))
此实现与实际实现有两点不同:
Just for completeness, this implementation differs from the actual implementation in two ways:
-
空参数列表
Empty argument list
;; actual implementation
(apply +)
;=> ArityException Wrong number of args (1) passed to: core/apply
;; my implementation
(apply +)
;=> 0
懒惰
Laziness
;; actual implementation
(apply apply == (range))
;=> StackOverflowError
;; my implementation
(apply apply == (range))
;=> false
这篇关于函数`apply`的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!