clojure 中的匿名函数需要多少个参数? [英] How many arguments does an anonymous function expect in clojure?

查看:28
本文介绍了clojure 中的匿名函数需要多少个参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Clojure 如何确定匿名函数(使用 #... 符号创建)期望多少个参数?

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 "Hello, world!") -> no arguments

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

#(println (str "Hello, " % "!")) -> 1 argument (% is a synonym for %1)

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

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

and so on. Note that you do not have to use all %ns, 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").

来自 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.

这篇关于clojure 中的匿名函数需要多少个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆