Whenever in Haskell we need some variant data type, we would use ADTs in conjunction with pattern matching. What do Clojure folks use for such use cases?
Whenever in Haskell we need some variant data type, we would use ADTs in conjunction with pattern matching. What do Clojure folks use for such use cases?
It's possible to use multimethods and macros.
One example can be found below.
So how do they look in Clojure?
The syntax that this ADT implementation will use will look like this:
(defadt Tree (Empty) (Leaf value) (Node left right))This syntax is incredibly similar to the Haskell code. We will also see that we can define the depth function described above like so:
(defmulti depth adt-type) (defmethod depth Empty [_] 0) (defmethod depth Leaf [_] 1) (defmethod depth Node [node] (+ 1 (max (depth (node :left)) (depth (node :right))))) (defmethod depth :default [_] 0)
Source: http://gizmo385.github.io/clojure/programming/2015/08/11/adts-in-clojure.html