Hi,

Am 09.06.2009 um 08:50 schrieb Josh Smith:

I've been trying to understand the macro syntax in clojure.  I think
macro's are closer to the kind of functionality I'm looking for (as
opposed to multi-methods) but I'm not sure.

Ask yourself the following question:

        Does what you want to do need to happen
        at compile time?

If the answer is "no", macros are not the way to go.

Here are some reasons you don't want macros:

- they are static, changing them requires recompilation
  of the code which uses them.

- they need to be clash-safe, locals need to be generated,
  although Clojure has the # notation this might lead to
  subtle problems if multiple ` forms are involved

- they need to take care to not evaluate their arguments
  multiple times, this can be tedious to track and easy
  to miss when changing a more complicated macro

- they cannot be passed to other functions, not be
  applied etc.

Looking at your macros, the main reason you need
macros is, because you want to treat methods as
first class citizen, which they are not. You can either
result to manually use reflection or you wrap them
a little more.

Here is an example how your m_load_properties
could look like...

(defn- load-pairs-handler
  [prop]
  (.load prop))

(defn- load-xml-handler
  [prop]
  (.loadFromXML prop))

(defn load-properties
  [filename load-handler]
  (with-open [ifst (java.io.FileInputStream. filename)]
   (let [prop    (doto (new java.util.Properties)
                   (load-handler prop))
         keysseq (enumeration-seq (.propertyNames prop))
         valsseq (map #(.getProperty prop %) keysseq)]
     (zipmap keysseq valsseq))))

(load-properties "some_file.properties" load-pairs-handler)

You could also use multimethods. They could
dispatch on the filename...

(defmulti load-properties
  {:arglists '([filename])}
  (fn [s] (subs s (.lastIndexOf s "."))))

(defmethod load-properties "xml"
  ...)

(defmethod load-properties "properties"
  ...)

I think there are some ways to handle that without a macro.

Hope this helps.

SIncerely
Meikel

Attachment: smime.p7s
Description: S/MIME cryptographic signature

Reply via email to