Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional Programming with Clojure

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!

like image 425
todun Avatar asked Dec 21 '25 06:12

todun


2 Answers

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.

like image 66
nickmbailey Avatar answered Dec 23 '25 00:12

nickmbailey


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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!