emacs-devel
[Top][All Lists]
Advanced

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

Re: Pattern matching on match-string groups #elisp #question


From: Mattias Engdegård
Subject: Re: Pattern matching on match-string groups #elisp #question
Date: Fri, 26 Feb 2021 11:24:48 +0100

26 feb. 2021 kl. 05.31 skrev Stefan Monnier <monnier@iro.umontreal.ca>:

> Good question.  I'm not sure how best to explain or document it, sadly.
> One of the reasons is that predicates are presumed to be (mostly) pure
> functions, so `pcase` feels free to call them fewer times or more times
> as it pleases.
> 
> But that also largely applies to `app`, so that's not a very
> good explanation.
> 
> Maybe a better explanation is that `pcase-let` optimizes the pattern
> match code under the assumption that the pattern will match, so it skips
> the tests that determine whether the pattern matches or not.
> 
> [ That doesn't mean it skips all the tests: if the pattern is
>  (or `(a ,v) `(b ,_ ,v)) it *will* test to see if the first element is `a` in
>  order to decide what to bind `v` to, but it won't bother to check if
>  the first element is `b` since it presumes that the pattern does match
>  and it knows that there's no further alternative.  ]
> 
> Note that this explanation is not very convincing either because it's
> not clear if the test that it skipped is `(identity VAR)`
> or `(identity (string-match ...))` so it's unclear whether the
> `string-match` is eliminated.

Thank you, I think this is good enough -- I've pushed the fix (with tests, so 
it matters less whether I've understood it) to master. (If pcase one day gets 
uppity enough to optimise based on the target expression as well, then a lot of 
tests will become meaningless.)

A clearer but less efficient pattern would be something like

(app (lambda (s) (and (string-match REGEXP s)
                      (list (match-string 1 s)
                            (match-string 2 s)
                            ...)))
     `(,VAR1 ,VAR2 ...))

which would, unless I'm mistaken, be the only way if string-match returned a 
match object instead of setting global match data.
Of course a sufficiently optimising compiler would eliminate the consing!

> It's linked to the special undocumented pcase pattern `pcase--dontcare`
> (whose name is not well chosen, suggestions for better names are
> welcome)

pcase--give-up
pcase--!,fail




reply via email to

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