You can also pass functions (and closures) around in a map;

(defn my-app-uses-do-something
  [map-with-cfg-stuff]
  ...
  ((:do-something map-with-cfg-stuff) 13 19)) )

(defn do-something-quickly [x y] ...
(defn do-something-elegantly [x y] ...

(my-app-uses-do-something
  {:do-something do-something-quickly
   :some-other-cfg-stuff [...whatever] } )

Another little example to drive home the point;

(defn uses-f [mp x y] ((:f mp) x y))

(defn f [x y] (+ x y))

(uses-f {:f f} 3 4)
7
uses-f {:f -} 3 4)
-1
(uses-f {:f #(+ (* %1 %2) 3)} 3 4)
15

It's really worthwhile getting one's head around higher order
functions and closures. It allows you to totally think out of the
(imperative) box. Don't pass the data to a function - pass the
function to some data!

Rgds, Adrian.


On Thu, Jul 16, 2009 at 10:33 PM, John Harrop<jharrop...@gmail.com> wrote:
> On Thu, Jul 16, 2009 at 11:34 AM, Dragan <draga...@gmail.com> wrote:
>>
>> Thanks for the tip, I meant something else.
>> Let's say that I want to write a function do-something. There could be
>> 2 implementations: do-something-quickly and do-something-elegantly.
>> The parameters are the same and there are no differences in their
>> "interface". I would like to be able to call it by  writing (do-
>> something arg) in my code and specify which implementation I want to
>> use somewhere else (in the configuration part of the code).
>
> Functions are values you can pass around, so:
> (defn do-something-quickly [x y] ... )
> (defn do-something-elegantly [x y] ... )
> (defn do-various-things [do-something x y z w]
>   (let [z (do-something x y)]
>     ... ))
> user=> (do-various-things do-something-quickly 13 19 3 23)
> some-sort-of-output
> user=> (do-various-things do-something-elegantly 13 19 3 23)
> some-sort-of-output
>
> >
>

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to