On Sep 24, 10:59 am, Miron Brezuleanu <mbr...@gmail.com> wrote: > Well, I only want to enforce duck-typing :-) - for instance, make sure > via unit tests that a function that should return a data structure > with certain properties always returns such a data structure.
Not exactly what you asked for, but I added a defstruct* helper to my utils.clj. I'm still not entirely sure it's a good idea, but here it is: (defmacro defstruct* "Wrapper for defstruct which also creates a simple duck type checking function." [name & slots] `(do (defstruct ~name ~...@slots) (defn ~(symbol (str "is-" name "?")) [x#] (if (map? x#) (let [sample# (struct ~name)] (empty? (clojure.set/difference (set (keys sample#)) (set (keys x#))))) false)))) Use it just like you use defstruct, e.g.: (defstruct* person :first- name :last-name :age), but it will also create a little type-checker function: is-person? Here are some tests to see how it works: (defstruct* duck-typed-struct :a :b :c) (deftest duck-typed-predicates (let [dt1 (struct duck-typed-struct 1 2 3) dt2 {:a 4 :b 5 :c 6} dt3 (struct duck-typed-struct 1 2) dt4 {:a 4 :b 5 :c nil} not-dt1 {:a 4 :b 5} not-dt2 {:d 7 :e 8} not-dt3 {:a 4 :b 5 :d 7}] (is (is-duck-typed-struct? dt1)) (is (is-duck-typed-struct? dt2)) (is (is-duck-typed-struct? dt3)) (is (is-duck-typed-struct? dt4)) (is (not (is-duck-typed-struct? not-dt1))) (is (not (is-duck-typed-struct? not-dt2))) (is (not (is-duck-typed-struct? not-dt3))))) --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---