Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 693
zw0rk Avatar asked Mar 25 '11 09:03

zw0rk


2 Answers

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.

like image 86
Maurits Rijk Avatar answered Nov 11 '22 21:11

Maurits Rijk


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.

like image 39
hawkeye Avatar answered Nov 11 '22 21:11

hawkeye