How many arguments does an anonymous function expect in clojure?

前端 未结 3 870
北荒
北荒 2020-12-03 13:48

How does Clojure determine how many arguments an anonymous function (created with the #... notation) expect?

user=> (#(identity [2]) 14)
java         


        
3条回答
  •  [愿得一人]
    2020-12-03 14:34

    #(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 %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").

    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.
    

提交回复
热议问题