As Laurent says, you should just use the built-in `identity` function,
but you can write it yourself: as you noticed, (fn [x] x) works, but
if you want to do it with the shorthand syntax you can use #(do %).

On Sep 4, 1:56 pm, julianrz <julia...@yahoo.com> wrote:
> Hello All,
> I am new to Clojure. Surprised why this code does not work:
>
> user=> (filter #(%) [1 2 3])
> ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn
>
> Here my intent behind #(%) is to define a lambda function returning
> its argument. Since Clojure defines truth on any type, it should be
> acceptable as filter function, and the result should be the original
> array
>
> Some narrowing down. What's #(%) really good for?
>
> user=> #(%)
> #<user$eval48$fn__49 user$eval48$fn__49@5e2c17f7>
>
> so it is a function
>
> user=> (#(%))
> ArityException Wrong number of args (0) passed to: user$eval26$fn
>
> Ok, here not enough arguments supplied, fair enough. Let's fix that:
> user=> (#(%) 1)
> ClassCastException java.lang.Long cannot be cast to clojure.lang.IFn
>
> Same problem as the first example. So Clojure understands this is a
> function, knows it takes some arguments, but cannot call it? What's
> wrong? The following works:
>
> (user=> (filter (fn [a] a) [1 2 3])
> (1 2 3)
>
> So apparently it has something to do with the fact that #() is
> shorthand. So in my case, it produces a function which cannot be
> used... In fact, it seems to just yield the constant, not a function.
> Ask me, it should work (auto-wrap the constant in a function) or the
> expression should be illegal. I think it deserves better
> diagnostics...
>
> Also, in Practical Clojure book, it says: "The shothand function form
> #(* %1 %2) is actually identical to the longer form (fn [x y] (* x y))
> before it is even seen by the compiler." If you literally apply this
> rule, you will get
>
> ((fn[x] (1)) 1)
>
> which throws same exception, not surprisingly, since it tries to
> evaluate 1 as a fucntion. What it should have done is transform the
> expression into
>
> ((fn[x] 1) 1)
>
> which works fine... Special-case it?
>
> What do you think?
>
> Julian

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to