A pattern guard proposal Daphne Preston-Kendal (02 Sep 2025 11:51 UTC)
Re: A pattern guard proposal John Cowan (05 Sep 2025 20:12 UTC)
Re: A pattern guard proposal Daphne Preston-Kendal (26 Sep 2025 11:39 UTC)

A pattern guard proposal Daphne Preston-Kendal 02 Sep 2025 11:51 UTC

If SRFI 262 is going to support pattern guards, I think SuccessorML’s model is the best to emulate – with a slight twist to allow custom pattern syntax to take advantage of it.

The syntax of match clauses will change to be one of:

(<<pattern>> <<body>>) as now, or
(<<pattern>> <<guard clause>> <<body>>)

The syntax of clauses for match-values and match-lambda changes similarly, mutatis mutandis.

<<Guard clause>> must be one of the new pieces of auxiliary syntax:

(guard-with <<expression>> <<extra pattern>>)
(guard-if <<expression>>)

Guard-with evaluates <<expression>> in an environment that has all the pattern variables from <<pattern>> in scope, then tests the result of evaluating that expression against the <<extra pattern>>.
Guard-if is similar, but instead of testing the result against an extra pattern it just makes sure it evaluates to a true value. (It is in fact basically syntactic sugar for (guard-with <<expression>> (not #f)).)

This syntax is unambiguous because guard-with and guard-when are auxiliary syntax only, not valid expressions in a <<body>>.

To enable pattern syntax to make use of this, guard-with and guard-if are also patterns themselves:

(guard-with <<pattern>> <<expression>> <<extra pattern>>)
(guard-if <<pattern>> <<expression>>)

As patterns, these test the <<pattern>> against the subject, evaluate the <<expression>> in an environment containing the pattern variables of the subpattern (not any pattern variables outside), and then either test against the <<extra pattern>> or simply succeed if the expression’s value is true respectively, like their guard clause counterparts.

Incidentally, this also demonstrates why my strategy for dealing with disjointed variables was correct. With these guard-type subpatterns, custom pattern syntax can hygienically bind pattern variables for use in guard expressions of their own devising, and it will not cause any problems in composing that pattern syntax with ‘or’ patterns :-)

Are there any thoughts on this?

Daphne