Reputation: 165
gurus
Here's a question for you: I am working on a clojure program that involves passing functions to functions.
I have something like:
(defn funct-op [args]
((first args)
(second args)
(last args) )
(funct-op '(+ 2 2))
How can I coax funct-op into giving me 4 rather than the 2 I am currently getting? I may need to pass a function to a macro as my project progresses. Any tips on how to do that? Thanks for your help!
Upvotes: 3
Views: 219
Reputation: 40155
I'm not sure, these things?
(defn funct-op [f list]
(apply f list))
(funct-op + '(1 2));=>3
Upvotes: 1
Reputation: 3684
In order to turn the '+' into a function you can use resolve. This should work on core functions, but you may need ns-resolve for custom functions. You can then use apply to pass the rest of the arguments to that function.
(defn funct-add [args] (apply (resolve (first args)) (rest args)))
Not sure what your end goal really is but I think that is the answer you were looking for.
Upvotes: 4
Reputation:
What is funct-add
really supposed to do? What if it was (funct-add '(- 2 2))
?
Anyway, consider apply, even wrapped up:
(defn apply-wrapper [args]
(apply (first args) (rest args)))
; note use of of the [...] form
(apply-wrapper [+ 2 2]) ; => 4
(apply-wrapper [- 2 2]) ; => 0
Comparing these forms may be enlightening:
(+ 1 2) ; 3
'(+ 1 2) ; (+ 1 2)
[+ 1 2] ; [#<core$_PLUS_ clojure.core$_PLUS_@a8bf33> 1 2]
Note how the last one was evaluated; it is not just a "literal list" -- no symbol there anymore! :-)
Happy coding.
Upvotes: 4