Hi.

I'm developing a simple pattern matching library for clojure but I am
having
trouble with macros (which I have almost zero experience with).

I have a function `make-matcher`

(make-matcher <pattern>)

which returns a function that can pattern match on data and returns a
map of bindings (or nil in case of a non-match).

((make-matcher '(list x y z w)) (list 1 2 3 4))
; => {x 1 y 2 z 3 w 4}
((make-matcher '(list x y z x)) (list 1 2 3 4))
; => nil
((make-matcher '(list 1 x 2 _)) (list 1 2 3 4))
; => nil
((make-matcher '(list 1 x 2 _)) (list 1 3 2 9))
; => {x 3}

I have been trying to write the following 'match' macro:

(match <data>
  <pattern-1> <body-1>
  <pattern-2> <body-2>)

The macro should work like this:

(match (list 1 2 3)
       (list 1 x)   (+ x x)
       (list 1 x y) (+ x y))
; => 5

I have the following macros (none of which works correctly):

; (letmap {a 1 b 2} (+ a b))
; =(should) expand to=>
; (let [a 1 b 2] (+ a b))
(defmacro letmap [dict & body]
  `(let ~(into [] (reduce concat (eval dict)))
     (do ~...@body)))

; (match (list 1 2 3)
;       (list 1 x)   (+ x x)
;       (list 1 x y) (+ x y))
; =should expand to something like=>
; (let [dict (<matcher..> (list 1 2 3))]
;   (if dict
;      (letmap dict (+ 1 x))
;      (match (list 1 2 3) (list 1 x y) (+ x y))))
(defmacro match [data & clauses]
  (when clauses
    (let [pattern    (first clauses)
          body       (second clauses)
          matcher (make-matcher pattern)]
      `(let [dict# (~matcher ~data)]
         (if dict#
           (letmap dict# ~body)
           (match ~data (next (next ~clauses))))))))

Any help is appreciated. Also pointers to documents and books where I
can
learn more about macros.

Thanks.

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to