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: Sat, 26 Mar 2022 13:41:26 -0400


Based on the results of the ensuing discussion, I decided to refine my macro to just be one coherent defun. I experimented with a few different ways to do this, but settled on something that seemed relatively clear and minimal, with pattern matchers that seemed like a better fit for arglists than what exists in pcase already (but it's all pcase under the hood).

To give a flavor of what it looks like in practice, here's a few pattern defuns from the test:

(defun-pattern fibonacci
   "Compute the fibonacci sequence."
    ((0) 0)
    ((1) 1)
    ((n)
      (+ (fibonacci (- n 1))
           (fibonacci (- n 2)))))

(defun-pattern crit
 "D&D 5e critical hit computation, taking in the results of a d20
and a list of attributes currently in effect.  Returns whether the
results are a crit or not."
  ((20 _) t)
  ((19 (pred (member 'improved-crit))) t))

I'm attaching the package, which works, although there's some non-ideal parts of the implementation. If people think it is valuable, I can add this to GNU ELPA.

Attachment: defun-pattern.el
Description: application/emacs-lisp

Attachment: defun-pattern-test.el
Description: application/emacs-lisp



On Sat, Dec 18, 2021 at 11:53 PM Andrew Hyatt <ahyatt@gmail.com> wrote:
Hi all,

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"

This is all accomplished by a few small but tricky macros and a hashtable that holds all the rules.

I find this method of programming quite useful for certain kinds of problems, and pcase is close to what I want, but using pcase forced me to encapsulate all of my pattern matching logic in one function. Being able to have it spread out in pattern matching functions seems much nicer to me.

If this is of interest, I can either add this to the pcase module itself, create a package in gnu elpa, or (if there's some reason that it shouldn't be done) just keep it in a personal repository.

I'll wait for some guidance before creating a final version, with tests, wherever it should go.

reply via email to

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