匿名函数在clojure中期望有多少个参数?

时间:2011-10-20 20:09:45

标签: clojure arguments anonymous-function

Clojure如何确定匿名函数(使用#...表示法创建)所期望的参数数量?

user=> (#(identity [2]) 14)
java.lang.IllegalArgumentException: Wrong number of args (1) passed to: user$eval3745$fn (NO_SOURCE_FILE:0)

3 个答案:

答案 0 :(得分:33)

#(println "Hello, world!") - >没有参数

#(println (str "Hello, " % "!")) - > 1个参数(%%1

的同义词

#(println (str %1 ", " %2 "!")) - > 2个论点

等等。请注意,您不必使用所有%n s,预期的参数数量由最高n定义。所以#(println (str "Hello, " %2))仍然需要两个参数。

您还可以使用%&捕获其他参数,如

(#(println "Hello" (apply str (interpose " and " %&))) "Jim" "John" "Jamey")

来自Clojure docs

Anonymous function literal (#())
#(...) => (fn [args] (...))
where args are determined by the presence of argument literals taking the 
form %, %n or  %&. % is a synonym for %1, %n designates the nth arg (1-based), 
and %& designates a rest arg. This is not a replacement for fn - idiomatic 
used would be for very short one-off mapping/filter fns and the like. 
#() forms cannot be nested.

答案 1 :(得分:11)

它给你的错误是你将一个参数传递给期望为零的匿名函数。

匿名函数的arity由内部引用的最高参数决定。

e.g。

(#(identity [2])) - > arity 0,必须传递0个参数

(#(identity [%1]) 14) - > arity 1,1必须通过论证

(#(identity [%]) 14) - > (%%1的别名,当且仅当arity为1)时,必须传递1个参数

(#(identity [%1 %2]) 14 13)

(#(identity [%2]) 14 13) - > arity 2,2必须传递参数

(#(identity [%&]) 14) - > arity n,可以传递任意数量的参数

答案 2 :(得分:4)

您需要引用%1,%2等参数,以使函数需要许多参数。