Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In clojure, how to write the identity function using the anonymous function literal?

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?

like image 600
viebel Avatar asked Feb 05 '12 11:02

viebel


People also ask

What is FN in Clojure?

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

How do you return a function in Clojure?

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.

What are anonymous functions in JavaScript?

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.

Does Clojure have closures?

Clojure has closures, and closures are an excellent way to group functions (Crockford 2008) with their supporting data.


1 Answers

Well, first of all, there is the identity function.

But you can use

#(do %)

if you insist.

like image 115
Peteris Avatar answered Sep 20 '22 22:09

Peteris