v4gil
v4gil

Reputation: 911

Clojure how to send some args to a function that is called as a symbol

What I'm trying to do is call a function from a map with some locally defined variables without expressing the whole variable in the call to the function.

For example, the following code works, :

(let [a [0 1 2]]
  (eval (list ({:fun 'count} :fun) a))) => 3

and this code works for a quoted 'a when it is globally defined:

(def a [0 1 2])
(eval (list ({:fun 'count} :fun) 'a))

but this code does not work:

(let [a [0 1 2]]
  (eval (list ({:fun 'count} :fun) 'a))) 
=> Unable to resolve symbol: a in this context

The first chunk is fine for small vectors like this one, but when I need to pass in a vector of several thousand items then the unquote "a" would cause it to throw an error for "Method too large" because the actual method sent to the machine is:

(let [a [0 1 2]]
  (eval (count [0 1 2]))

What is a simple way to execute a call to the function with the variable itself as an argument?

Upvotes: 0

Views: 137

Answers (1)

Thumbnail
Thumbnail

Reputation: 13483

It isn't clear why you are evaling the symbol 'count. Can't you just keep the function count in the map and call it as follows:

(let [a [0 1 2]] (({:fun count} :fun) a)) => 3

Then vector a can be any size you like.


  • Don't use an eval where a macro will do.
  • Don't use a macro where a function will do.

In retrospect, all you have done is defer compilation from when it is easy to when it is difficult.

Upvotes: 1

Related Questions