开发者

Clojure algebraic data types

开发者 https://www.devze.com 2023-02-19 22:11 出处:网络
I\'ve found defadt macro in clojure.contrib.types. U开发者_运维知识库nfortunately, there is no useful documentation on ADTs usage in clojure. I\'ve googled for hours and found tiny pieces of informati

I've found defadt macro in clojure.contrib.types. U开发者_运维知识库nfortunately, 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消