Re: pattern-matching in LISP?
- From: Alan Crowe <alan@xxxxxxxxxxxxxxxxxxxxxxx>
- Date: 29 Apr 2007 21:08:21 +0100
Chris Schumacher <kensu__@xxxxxxxxxxx> writes:
But it didn't appear to work. Does LISP have pattern-matching capabilities
as well?
destructing-bind doesn't do quite what you need. The catch
is that
Exceptional Situations:
If the result of evaluating the expression does not
match the destructuring pattern, an error of type error
should be signaled.
Checking the error terminology page to see what this means
1.4.2 Error Terminology
An error is signaled
This means that an error is signaled in both safe and
unsafe code. Conforming code may rely on the fact that
the error is signaled in both safe and unsafe code.
An error should be signaled
This means that an error is signaled in safe code, and
an error might be signaled in unsafe code.
Damn, the designers went for "should be" instead of
"is". Clearly they thought of the match checking code as a
debugging aid that might go away when you optimize for
speed.
All is not lost. The Common Lisp has a fairly powerful type
system. For example (cons * (cons * null)) names the type of
a list of two items. You can replace * by something more
specific.
So you can duct tape typecase and destructuring-bind
together like this:
CL-USER> (defun flex (x)
(typecase x
(atom x)
((cons integer (cons integer null))
(destructuring-bind (a b) x
(+ a b)))
((cons float (cons float null))
(destructuring-bind (a b) x
(* a b)))
((cons * *)
(destructuring-bind (a . b) x
(expt a b)))))
CL-USER> (dolist (x '(1
(5 7)
(5.0 7.0)
(2 . 3)))
(format t "~&~A ~A" x (flex x)))
1 1
(5 7) 12
(5.0 7.0) 35.0
(2 . 3) 8
Alan Crowe
Edinburgh
Scotland
.
- References:
- pattern-matching in LISP?
- From: Chris Schumacher
- pattern-matching in LISP?
- Prev by Date: Re: What are the domains that lisp doesn't fit int?
- Next by Date: Re: copying arrays
- Previous by thread: Re: pattern-matching in LISP?
- Next by thread: Opposite of ~^ FORMAT Directive
- Index(es):