diff options
author | Konrad Hinsen <konrad.hinsen@laposte.net> | 2009-02-25 15:11:11 +0000 |
---|---|---|
committer | Konrad Hinsen <konrad.hinsen@laposte.net> | 2009-02-25 15:11:11 +0000 |
commit | 9317a7a1ee19c49e9eccfc5523c8fc84c42ec6f6 (patch) | |
tree | 77e4b9280949ba1cdd4d36d67ce0f6de1586f57f /src/clojure/contrib/types | |
parent | 7631cfad764e954fc12840466698e85ede9674e6 (diff) |
New library clojure.contrib.types implements algebraic data types
Diffstat (limited to 'src/clojure/contrib/types')
-rw-r--r-- | src/clojure/contrib/types/examples.clj | 81 |
1 files changed, 81 insertions, 0 deletions
diff --git a/src/clojure/contrib/types/examples.clj b/src/clojure/contrib/types/examples.clj new file mode 100644 index 00000000..26421697 --- /dev/null +++ b/src/clojure/contrib/types/examples.clj @@ -0,0 +1,81 @@ +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Application examples for algebraic data types +;; +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +(ns clojure.contrib.types.examples + (:use clojure.contrib.types)) + +; +; A simple tree structure +; +(deftype tree + empty-tree + (leaf value) + (node left-tree right-tree)) + +(def a-tree (node (leaf :a) + (node (leaf :b) + (leaf :c)))) + +(defn depth + [#^tree t] + (match t + empty-tree 0 + (leaf n) 1 + (node l r) (inc (max (depth l) (depth r))))) + +(depth empty-tree) +(depth a-tree) + +; +; Algebraic data types with multimethods: Haskell-style functors +; +(defmulti fmap (fn [f s] (class s))) + +; Sequences +(defmethod fmap clojure.lang.ISeq + [f s] + (map f s)) + +; Vectors +(defmethod fmap clojure.lang.IPersistentVector + [f v] + (into [] (map f v))) + +; Trees +(defmethod fmap tree + [f t] + (match t + empty-tree empty-tree + (leaf v) (leaf (f v)) + (node l r) (node (fmap f l) (fmap f r)))) + +(fmap str '(:a :b :c)) +(fmap str [:a :b :c]) +(fmap str a-tree) + +; +; Nonsense examples to illustrate all the features of match +; +(deftype foo + (bar a b c)) + +(defn foo-to-int + [a-foo] + (match a-foo + (bar x x x) x + (bar 0 x y) (+ x y) + (bar 1 2 3) -1 + (bar a b 1) (* a b) + :else 42)) + +(foo-to-int (bar 0 0 0)) +(foo-to-int (bar 0 5 6)) +(foo-to-int (bar 1 2 3)) +(foo-to-int (bar 3 3 1)) +(foo-to-int (bar 0 3 1)) +(foo-to-int (bar 10 20 30)) |