emacs-devel
[Top][All Lists]
Advanced

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

Re: pcase defuns


From: Andrew Hyatt
Subject: Re: pcase defuns
Date: Sun, 19 Dec 2021 10:33:12 -0500

On Sun, Dec 19, 2021 at 09:34 AM Tassilo Horn <tsdh@gnu.org> wrote:
Andrew Hyatt <ahyatt@gmail.com> writes: Hi Andrew,
As a part of a personal project, I wrote a way to define functions in an equivalent way to pcases. For example: (pcase-defun mytest (a b _) "Match on 'a 'b with the third argument a wildcard" "a b match") (pcase-defun mytest (c ,var _) "Match on 'c binding VAR, with the third argument a wildcard" (format "c %s match" var) ) (mytest 'a 'b 'c) -> "a b match" (mytest 'c 100 'c) -> "c 100 match"

So that's basically similar to cl-defgeneric / cl-defmethod just with pcase pattern matching, right? In that case, I think I like the cl approach better, i.e., having a separate definition for the signature + several implementations for variants. But since the order of patterns is very significant, I'm not sure if it's a good idea to specify them separately. E.g., what if there are pcase-defun's for mytest in several files? Then you might get different behavior depending on the order how files are loaded. And even in the "all patterns in mytest.el" case: what if I re-evaluate some pcase-defuns after the file has been loaded?

I have a solution for this: a crude one: I just sort all the rules according to their flattened length. So the most complicated ones should get tried first, which I think is something that can communicated to the user. There's other ways the system could behave, such as offering to the user to define a priority for the rule. But definitely it's easy to make sure new rules can be added without crazy things happening.

You've hit upon the issue with these types of systems. Powerful, easy to use, but dispatch rules are always vague. The same thing can happen with cl-defmethod, IIRC, where you can have two rules that both seem like they should take precedence. I think offering this functionality gives the user that choice - if they want very specific ordering, they can just use pcase in a function, either in a solution as you propose, or just use pcase itself, which is pretty straighforward.


So probably I'd favor a pcase-defun which specifies all patterns and
bodies in a single definition, e.g., like:

(pase-defun mytest
  "Docstring"
 ((a b _)
  "a b match")
 ((c ,var _)
  (format "c %s match" var)))

Bye,
Tassilo



reply via email to

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