clojure 中的匿名函数需要多少个参数?
Clojure 如何确定匿名函数(使用 #...
符号创建)需要多少个参数?
user=> (#(identity [2]) 14)
java.lang.IllegalArgumentException: Wrong number of args (1) passed to: user$eval3745$fn (NO_SOURCE_FILE:0)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
#(println "你好,世界!")
->无参数#(println (str "Hello, " % "!"))
-> 1 个参数(%
是%1
的同义词)#(println (str %1 ", " %2 "!"))
- > 2 论证等等。请注意,您不必使用所有
%n
,预期的参数数量由最高的 n 定义。因此#(println (str "Hello, " %2)) 仍然需要两个参数。您还可以使用
%&
捕获剩余参数,如(#(println "Hello" (apply str (interpose " and " %&))) "Jim" "John" “杰米”)
。来自 Clojure 文档:
#(println "Hello, world!")
-> no arguments#(println (str "Hello, " % "!"))
-> 1 argument (%
is a synonym for%1
)#(println (str %1 ", " %2 "!"))
-> 2 argumentsand 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:
它给你一个错误,你将一个参数传递给你的匿名函数,而该函数期望为零。
匿名函数的元数由内部引用的最高参数决定。
例如
(#(identity [2]))
-> arity 0, 0 个参数必须传递(#(identity [%1]) 14)
-> arity 1, 1 参数必须传递(#(identity [%]) 14)
-> (%
是%1
的别名,当且仅当参数数为 1 时),必须传递 1 个参数(#(identity [%1 %2] ) 14 13)
或(#(identity [%2]) 14 13)
->数量为 2,必须传递 2 个参数(#(identity [%&]) 14)
-> arity n,可以传递任意数量的参数It is giving you the error that you passed one argument to your anonymous function that was expecting zero.
The arity of an anonymous function is determined by the highest argument referenced inside.
e.g.
(#(identity [2]))
-> arity 0, 0 arguments must be passed(#(identity [%1]) 14)
-> arity 1, 1 argument must be passed(#(identity [%]) 14)
-> (%
is an alias for%1
if and only if the arity is 1), 1 argument must be passed(#(identity [%1 %2]) 14 13)
or(#(identity [%2]) 14 13)
-> arity 2, 2 arguments must be passed(#(identity [%&]) 14)
-> arity n, any number of arguments can be passed您需要使用 %1、%2 等引用参数,以使函数需要那么多参数。
You need to refer to the arguments with %1, %2 etc. to cause the function to require that many arguments.