Clojure Algebraic Data Types

I found the defadt macro in clojure.contrib.types . Unfortunately, there is no useful documentation on using ADT in clojure. I searched the Internet for many hours and found tiny information about it. What is ADT in clojure? How to use them? Any information would be helpful :)

+6
algebraic-data-types clojure
source share
2 answers

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

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

Additional information in the source file.

+2
source share

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

Define an ADT generator as follows:

 (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 Clojure

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

This is pretty cool.

+1
source share

All Articles