3 ms·
The problem with patterns allowed to be expressions that simply evaluate to an object to be matched is that this gets in the way of doing potentially more usefu
by kazinator 3y ago
The problem with patterns allowed to be expressions that simply evaluate to an object to be matched is that this gets in the way of doing potentially more useful things, like predicates, so it's kind of a waste:
TXR Lisp:
1> (match (@a @(= (+ a 1))) '(1 3) a)
** match: (@a @(= (+ a 1))) failed to match object (1 3)
1> (match (@a @(= (+ a 1))) '(1 2) a)
1
An expression is treated as a predicate. The object being matched, like 2, is inserted as a right argument into it: (= (+ a 1) <obj>).
If you try the following, you get a surprising result:
2> (match (@a @(+ a 1)) '(1 3) a)
1
It is more verbose, but we can do more. We don't have to test for exact equality; e.g. @(< a) will match something that is greater than the previously matched a.
Capture a b that is greater than previously captured a:
3> (match (@a @(< a @b)) '(1 3) (list a b))
(1 3)
Or fail trying:
4> (match (@a @(< a @b)) '(1 0) (list a b))
** match: (@a @(< a @b)) failed to match object (1 0)
We could treat certain functions differently; since + isn't a relational function producing a Boolean result, equality could be inserted implicitly to generate a predicate.
But, rather than that hack, there is a different one: user-defined patterns. We can have @(+ a 1) as a pattern by defining + as a pattern operator:
1> (defmatch + (. args) ^@(= (+ ,*args)))
+
Then:
2> (match (@a @(+ a 1)) '(1 2) a)
1
3> (match (@a @(+ a 1)) '(1 3) a)
** match: (@a @(+ a 1)) failed to match object (1 3)