How could one write the identity function in clojure using anonymous function literal (#())?
The following code doesn't work:
(#(%) 5)
It raises an exception because it is converted to:
((fn[x] (x)) 5)
The problem in that when using #(), the function body is enveloped with parentheses. Any idea, how to elegantly overcome this?
Most Clojure code consists primarily of pure functions (no side effects), so invoking with the same inputs yields the same output. defn defines a named function: ;; name params body ;; ----- ------ ------------------- (defn greet [name] (str "Hello, " name) )
Functions Returning Functions and Closures Our first function will be called adder . It will take a number, x , as its only argument and return a function. The function returned by adder will also take a single number, a , as its argument and return x + a . The returned function form adder is a closure.
Anonymous Function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name.
Clojure has closures, and closures are an excellent way to group functions (Crockford 2008) with their supporting data.
Well, first of all, there is the identity
function.
But you can use
#(do %)
if you insist.
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