多少个参数的匿名函数期望Clojure的? [英] How many arguments does an anonymous function expect in clojure?
问题描述
如何Clojure的确定有多少争论一个匿名函数(与#...
标记创建的)期望?
用户=> (#(身份[2])14)
java.lang.IllegalArgumentException异常:用户$ eval3745 $ FN:ARGS(1)传递到数目错误(NO_SOURCE_FILE:0)
#(pnn血你好,世界!)
- >没有参数
#(的println(STR你好,%)!)
- > 1参数(%
是一个同义词%1
)
#(的println(STR%1,%2)!)
- > 2的参数
和等。请注意,您不必利用N S,预期参数的数量由最高的N个所定义的所有%。因此,
#(的println(STR你好,%2))
仍然需要两个参数。
您也可以使用%安培;
来捕捉其余ARGS在
(#(的println你好(适用STR(干预和%&安培;)))吉姆,约翰詹姆)。
从 Clojure的文档:
匿名函数文本(#())
#(...)=> (FN [参数](...))
其中,ARG游戏通过采取论证文字的presence确定
形式%,%n或%放;. %是1%的代名词,%N指定的第n个ARG(1型)
和%安培;指定休息ARG。这不是FN的替代品 - 成语
使用将是非常短的一次性映射/过滤FNS和类似物。
#()的形式不能嵌套。
How does Clojure determine how many arguments an anonymous function (created with the #...
notation) expect?
user=> (#(identity [2]) 14)
java.lang.IllegalArgumentException: Wrong number of args (1) passed to: user$eval3745$fn (NO_SOURCE_FILE:0)
#(println "Hello, world!")
-> no arguments
#(println (str "Hello, " % "!"))
-> 1 argument (%
is a synonym for %1
)
#(println (str %1 ", " %2 "!"))
-> 2 arguments
and so on. Note that you do not have to use all %n
s, the number of arguments expected is defined by the highest n. So #(println (str "Hello, " %2))
still expects two arguments.
You can also use %&
to capture rest args as in
(#(println "Hello" (apply str (interpose " and " %&))) "Jim" "John" "Jamey")
.
From the 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.
这篇关于多少个参数的匿名函数期望Clojure的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!