murtaza52
murtaza52

Reputation: 47431

returning a data type from a fn literal

The below expression works -

((fn[n][(take n (range))]) 10)

While the below throws an error -

(#([(take % (range))]) 10)

Why cant I just return a data type from a function literal ?

Upvotes: 3

Views: 81

Answers (2)

guilespi
guilespi

Reputation: 4702

If you absolutely want to return "data" from an anonymous function using the # reader macro just use do.

#(do [1 2])

As @Mars said you also have the alternative to use the vector function.

#(vector 1 2)

Upvotes: 3

Lee
Lee

Reputation: 144136

The # anonymous function macro expands into a fn form e.g.

#([1 2])

is expanded into (fn* [] ([1 2]))

as you can see, when this is called, the vector you are trying to return will be called as a function, which will fail as no arguments are provided. This is the same issue you have:

#([(take % (range))])

is expanded into

(fn* [x] ([(take x (range))]))

Upvotes: 4

Related Questions