Pure Danger Tech


navigation
home

Abstracting constant creation

10 Mar 2011

I was just writing some code to create URI constants representing the XSD data types and was able to abstract the creation of the constants.  This is impossible in Java but was pretty trivial in Clojure.

In case you’re curious, the code is something like this:

(ns puredanger.xsd-types
  (:use [ clojure.string :only (upper-case)])
  (:import [ java.net URI]))

(def XSD-NS "http://www.w3.org/2001/XMLSchema#")
(defn new-uri [s] (URI/create s))
(defn make-xsd-uri [frag] (new-uri (str XSD-NS frag)))

;; Create var constants like XSD-STRING for every built-in datatype in
;; the XSD schema specification
(doseq [t ["string" "integer" #_"and lots more"]]
  (intern *ns*
          (symbol (str "XSD-" (upper-case t)))
          (make-xsd-uri t)))

The doseq will run when this ns is loaded and for each of the constants in the list, it interns a new var with the current namespace, a symbol like XSD-STRING, and the URI created by make-xsd-uri.