Help with anonymous functions

7 views
Skip to first unread message

jsrodrigues

unread,
Oct 25, 2009, 10:38:07 AM10/25/09
to Clojure
Hi,

I'm trying to find the #(...) equivalent of (fn [] ...) for the
following case:

user=> (into {} (map (fn [x] [x (* x x)]) [1 2 3 4]))
{4 16, 3 9, 2 4, 1 1}

When I try the following:
user=> (into {} (map #([% (* % %)]) [1 2 3 4]))

I get the error:
java.lang.RuntimeException: java.lang.IllegalArgumentException: Wrong
number of args passed to: LazilyPersistentVector (NO_SOURCE_FILE:0)

I even tried the following:
user=> (macroexpand-1 '#([% (* % %)]))

And got the result from the macroexpand-1:
(fn* [p1__181] ([p1__181 (* p1__181 p1__181)]))

What am I doing wrong here?

Thanks,
John

Lauri Pesonen

unread,
Oct 25, 2009, 11:29:51 AM10/25/09
to clo...@googlegroups.com
Hi John,

2009/10/25 jsrodrigues <john.s.r...@gmail.com>:


>
> When I try the following:
> user=> (into {} (map #([% (* % %)]) [1 2 3 4]))

The #(...) form assumes that the is a function call and thus it is
implicitly wrapped in parens. That is, #(+ % %) becomes (fn [x] (+ x
x)). So in your code the anonymous function body becomes ([x (* x x)])
which is broken and results in the error you are seeing. To fix this
you need to use a function that creates a vector out of your arguments
rather than the literal vector notation, i.e. #(vector % (* % %))

user> (map #(vector % (* % %)) [1 2 3 4])
([1 1] [2 4] [3 9] [4 16])

> John

--
! Lauri

MarkSwanson

unread,
Oct 25, 2009, 12:58:10 PM10/25/09
to Clojure
Thanks Lauri. I was stuck on this too.

FYI this issue prompted me to submit a patch to improve the arity
error message:

http://groups.google.com/group/clojure/browse_thread/thread/de969a419a535a82

jsrodrigues

unread,
Oct 25, 2009, 1:15:46 PM10/25/09
to Clojure
Thanks for the help Lauri!

John

On Oct 25, 10:29 am, Lauri Pesonen <lauri.peso...@iki.fi> wrote:
> Hi John,
>
> 2009/10/25 jsrodrigues <john.s.rodrig...@gmail.com>:
Reply all
Reply to author
Forward
0 new messages