【问题标题】:How many arguments does an anonymous function expect in clojure?clojure 中的匿名函数需要多少个参数?
【发布时间】:2011-10-20 20:09:44
【问题描述】:

Clojure 如何确定匿名函数(使用#... 表示法创建)需要多少参数?

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

【问题讨论】:

    标签: clojure arguments anonymous-function


    【解决方案1】:

    #(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 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.
    

    【讨论】:

    • 在前 3 个代码示例中,在 println 周围加上额外括号的要点是什么?
    【解决方案2】:

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

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

    例如

    (#(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) -> arity 2,必须传递 2 个参数

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

    【讨论】:

    • 酷,简洁的例子%&。谢谢!
    【解决方案3】:

    您需要使用 %1、%2 等来引用参数,以使函数需要那么多参数。

    【讨论】:

      猜你喜欢
      • 2020-01-03
      • 2012-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多