Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many arguments does an anonymous function expect in clojure?

Tags:

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)
like image 995
Matt Fenwick Avatar asked Oct 20 '11 20:10

Matt Fenwick


People also ask

Can anonymous functions have parameters?

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.

What is the structure of an anonymous 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.

Why can the argument function be anonymous?

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.

What is anonymous function with example?

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();


1 Answers

#(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.
like image 160
Paul Avatar answered Oct 22 '22 16:10

Paul