Clojure algebraic data types

I've found defadt macro in clojure.contrib.types. Unfortunately, there is no useful documentation on ADTs usage in clojure. I've googled for hours and found tiny pieces of information about it. What are ADTs in clojure? How to use them? Any information will be helpful :)


Some information can be found in the examples.clj file in src/clojure/contrib/types. It shows an example of a tree structure defined as an adt:

(defadt ::tree
  empty-tree
  (leaf value)
  (node left-tree right-tree))

More info in the source file.


There is a really interesting example of ADT's in Clojure here:

We define an ADT generator like this:

(defmacro data
  [adt-name equals-sign & constructors]
  `(do
     (defn ~(symbol (str adt-name "?")) [~'obj]
       (= ~(str adt-name) (adt-name ~'obj)))
     ~@(for [[type-name & fields]
             (filter (partial not= '(|))
                     (partition-by (partial = '|) constructors))]
         (apply (partial emit-constructor adt-name type-name)
                 fields))))

Given the Haskell example:

data Tree a = Empty
        | Leaf a
        | Node Tree Tree

Then we write the Clojure

(data Tree = Empty | Leaf value | Node left right)

Which is pretty cool.

链接地址: http://www.djcxy.com/p/5746.html

上一篇: Java中的单例和继承

下一篇: Clojure代数数据类型