[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: pcase bindings in patterns with complicated logic

From: Thierry Volpiatto
Subject: Re: pcase bindings in patterns with complicated logic
Date: Sun, 14 Jan 2024 07:03:35 +0000

Richard Stallman <rms@gnu.org> writes:

> I'm trying to figure out how pcase behaves in terms of which pattern
> variables are actually bound, depending on which parts of a case's
> pattern succeeds in matching.  That wasn't clear to me from the docs I
> read.
> I tried this example:
> (setq x1 nil x2 nil y1 nil y2 nil)
> (pcase '(foo 5)
>   ((or `(,(and (pred symbolp) x1) ,(and (pred symbolp) y1))
>        `(,(and (pred symbolp) x2) ,(and (pred numberp) y2)))
>    `(,x1 ,y1 ,x2 ,y2)))
> => (nil nil foo 5)
> So it seems that unless a match for a variable is included in the
> branch of the matching tree that actually completes, its variable is
> not set.
> But then I tried
> (pcase '(foo 5)
>   ((or `(,(and (pred symbolp) a1) ,(and (pred symbolp) b1))
>        `(,(and (pred symbolp) a2) ,(and (pred numberp) b2)))
>    `(,a1 ,b1 ,a2 ,b2)))
> => (nil nil foo 5)
> That surrised me, since outside the pcase, all four variables
> are unbound and referring to them gets errors.

To avoid this you could write instead:

    (pcase '(foo 5)
      (`(,(and (pred symbolp) a1)
          ,(and (or (pred symbolp) (pred numberp)) b1))
       `(,a1 ,b1)))


reply via email to

[Prev in Thread] Current Thread [Next in Thread]