Been working on a macro for homework for a long time now but we are completely stuck, my teacher has limited time, and the deadline is far over the limit. This is our last try to solve this one.
The description is as follows:
We are gonna write a macro match-pattern that matches parameter expr against a number of parameters pattern_i. If it succeeds body_i is evaluated with the free variables in pattern_i bound during the evaluation.
A pattern is a s-expression
It must match exactly
The symbol quote can not be used
Expr should only be evaluated once
Example:
* (match-pattern '((foo bar) foo baz) ((car . car) `(:cons ,car ,car)) ((one two three) `(:three ,one ,two ,three))) (:THREE (FOO BAR) FOO BAZ)
Our tactic so far is something like this:
1
A match function that we planned to use in the macro for comparing patterns. (Maybe not completely right but you getting the point)
(defun match (sexpr1 sexpr2)
(cond ((and (consp sexpr1) (consp sexpr2))
(and (match (first sexpr1) (first sexpr2))
(match (rest sexpr1) (rest sexpr2))))
((and (atom sexpr1) (atom sexpr2))
t)
(t nil)))
2
We want to loop all the patterns against expr, and by passing them to our match function we will get back true or nil. If it's true we assign expr to the body of the pattern.
(defmacro match-pattern (sexpr &body body)
(cond
((match sexpr (car (car body))) (print "sexpr shall match with body here"))
((null (cdr body)) nil)
(t `(match-pattern sexpr ,@(cdr body)))))
3
Don't know how the matching is intended to work, we tried to use #'mapcar in combination with an anonymous lambda function but didn't get further than that.
Does this seem like a reasonable approach? Having a lot of problem with quotes. In the Example in the description there is a quote on expr but not on the ones in the patterns in the body, why is this? And why are there:three and :cons in the body?