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)
An anonymous function is a function with no name which can be used once they're created. The anonymous function can be used in passing as a parameter to another function or in the immediate execution of a function.
An anonymous function is a function that is not stored in a program file, but is associated with a variable whose data type is function_handle . Anonymous functions can accept multiple inputs and return one output. They can contain only a single executable statement.
Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function.
An anonymous function is a function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation. Normal function definition: function hello() { alert('Hello world'); } hello();
#(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With