Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Function From a String With the Function’s Name in Clojure

Tags:

How could I call a function with a string? e.g. something like this:

(call "zero?" 1) ;=> false 
like image 324
Ashley Williams Avatar asked Oct 03 '10 09:10

Ashley Williams


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.

Does Clojure have closures?

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


2 Answers

Something like:

(defn call [^String nm & args]     (when-let [fun (ns-resolve *ns* (symbol nm))]         (apply fun args))) 
like image 62
Alex Ott Avatar answered Oct 22 '22 13:10

Alex Ott


A simple answer:

(defn call [this & that]   (apply (resolve (symbol this)) that))  (call "zero?" 1)  ;=> false 

Just for fun:

(defn call [this & that]   (cond     (string? this) (apply (resolve (symbol this)) that)    (fn? this)     (apply this that)    :else          (conj that this)))  (call "+" 1 2 3) ;=> 6 (call + 1 2 3)   ;=> 6 (call 1 2 3)     ;=> (1 2 3) 
like image 42
leontalbot Avatar answered Oct 22 '22 12:10

leontalbot