Created
October 3, 2011 01:53
-
-
Save AlexBaranosky/1258277 to your computer and use it in GitHub Desktop.
macro to define match-based functions
This file contains 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
(ns playmatch | |
(:use [clojure.core.match.core :only (match)])) | |
(defn len [coll] | |
"calc the length of a sequence" | |
(match [coll] | |
[[]] 0 | |
[[f & r]] (inc (len r)))) | |
(defmacro defmatch [name bindings & patterns] | |
"macro to make match-based functions" | |
`(defn ~name ~bindings | |
(match ~bindings | |
~@patterns))) | |
(defmatch len [coll] | |
[[]] 0 | |
[[fst & rest]] (inc (len rest))) | |
(fact "voila!" | |
(len [\a \b \c]) => 3) | |
;; thoughts: that binding [coll] seems a little superfluous. With a more hairy/gnarly macro could gt rid of it, by inferring that length of each pattern's vector, and just making a vector from scratch to serve as the binding for the defn | |
;; That way we could just write: | |
(defmatch len | |
[[]] 0 | |
[[fst & rest]] (inc (len rest))) |
Author
AlexBaranosky
commented
Oct 3, 2011
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment