How could I call a function with a string? e.g. something like this:
(call "zero?" 1) ;=> false
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) )
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.
Clojure has closures, and closures are an excellent way to group functions (Crockford 2008) with their supporting data.
Something like:
(defn call [^String nm & args] (when-let [fun (ns-resolve *ns* (symbol nm))] (apply fun args)))
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With