Forked from robertpfeiffer/crude-haskell-like-matching.clj
Created
December 8, 2009 13:56
-
-
Save fogus/251639 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defprotocol Matchable (match [me matcher])) | |
(defmacro data [name & constructors] | |
`(do | |
(defprotocol ~name) | |
(defprotocol ~(symbol (str "match-"name)) | |
~@(for [[const & args] constructors] | |
`(~(symbol (str "match-"const)) [_# ~@args]))) | |
~@(for [[const & args] constructors] | |
(if (seq args) | |
`(defn ~const [~@args] | |
(reify [Matchable ~name] | |
(match [me# matcher#] | |
(~(symbol (str "match-"const)) matcher# ~@args)))) | |
`(def ~const | |
(reify [Matchable ~name] | |
(match [me# matcher#] | |
(~(symbol (str "match-"const)) matcher# ~@args)))))))) | |
(defmacro match* [type val & paths] | |
`(match ~val | |
(reify [~(symbol (str "match-"type))] | |
~@(for [[const args & code] paths] | |
`(~(symbol (str "match-" const)) [_ ~@args] ~@code))))) | |
(data List [Nil] [Cons car cdr]) | |
(defn my-map [fun aList] | |
(match* List aList | |
(Nil [] Nil) | |
(Cons [car cdr] (Cons (fun car) (my-map fun cdr))))) | |
(defn my-foldr [fun val aList] | |
(match* List aList | |
(Nil [] val) | |
(Cons [car cdr] (fun car (my-foldr fun val cdr))))) | |
(defn print-List [aList] | |
(print "(") | |
(my-map #(do (print %) (print " ")) aList) | |
(print ")")) | |
(print-List (Cons 2 (Cons 3 Nil))) | |
(my-foldr + 0 (Cons 2 (Cons 3 Nil))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment