Mat*_*ick 20 arguments clojure anonymous-function
Clojure如何确定匿名函数(使用#...符号创建)期望的参数数量?
user=> (#(identity [2]) 14)
java.lang.IllegalArgumentException: Wrong number of args (1) passed to: user$eval3745$fn (NO_SOURCE_FILE:0)
Run Code Online (Sandbox Code Playgroud)
Pau*_*aul 35
#(println "Hello, world!") - >没有参数
#(println (str "Hello, " % "!")) - > 1个参数(%是同义词%1)
#(println (str %1 ", " %2 "!")) - > 2个参数
等等.请注意,您不必使用全部%ns,期望的参数数量由最高n定义.所以#(println (str "Hello, " %2))仍然需要两个论点.
您还可以使用%&捕获休息参数
(#(println "Hello" (apply str (interpose " and " %&))) "Jim" "John" "Jamey").
来自Clojure文档:
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.
Run Code Online (Sandbox Code Playgroud)
Mat*_*ton 11
它给你的错误是你将一个参数传递给期望为零的匿名函数.
匿名函数的arity由内部引用的最高参数决定.
例如
(#(identity [2])) - > arity 0,必须传递0个参数
(#(identity [%1]) 14) - > arity 1,1必须通过1个参数
(#(identity [%]) 14)- >(if是且仅当arity为1时%为别名%1),必须传递1个参数
(#(identity [%1 %2]) 14 13) 要么
(#(identity [%2]) 14 13) - > arity 2,必须传递2个参数
(#(identity [%&]) 14) - > arity n,可以传递任意数量的参数