emacs-devel
[Top][All Lists]
Advanced

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

pcase-if-let?


From: Michael Heerdegen
Subject: pcase-if-let?
Date: Thu, 29 Mar 2018 01:20:50 +0200
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/27.0.50 (gnu/linux)

Hello,

should we add a `pcase-if-let' to pcase.el?  While the name might sound
a bit obscure, in my experience I quite often wanted something like
this, instead of having to write

#+begin_src emacs-lisp
(pcase value
  (pattern code
           more code
           ...)
  (_       other code
           more other code
           ...))
#+end_src

for example.

Here is the result of a first naive implementation trial (which works
for me):

#+begin_src emacs-lisp
(defmacro pcase-if-let (bindings then &rest elses)
  "Bind variables according to BINDINGS and eval THEN or ELSE.
This is like `if-let' but BINDINGS is a list of elements of the
form \(PATTERN VALUE-FORM) and it's tested whether all the
PATTERNs match instead of whether VALUE-FORMS are all non-nil."
  (declare (indent 2)
           (debug ((&rest (pcase-PAT &optional form))
                   form body)))
  (if (null bindings)
      '(let* () then)
    (let ((sym (make-symbol "sym"))
          (sucess-syms '())
          (last-sucess-sym nil))
      (dotimes (i (length bindings))
        (push (make-symbol (format "binding-%d-sucess" i)) sucess-syms))
      (cl-callf nreverse sucess-syms)
      `(progn
         (mapc (lambda (,sym) (setq ,sym nil)) ',sucess-syms)
         (pcase nil
           ((and ,@(mapcar (pcase-lambda (`(,pattern ,value))
                             `(let (and ,@(if last-sucess-sym `((guard 
,last-sucess-sym)) '())
                                        ,pattern
                                        (let ,(setq last-sucess-sym (pop 
sucess-syms)) t))
                                ,value))
                           bindings))
            (if ,last-sucess-sym ,then ,@elses)))))))
#+end_src

Note that there is no need for a `pcase-if' (just don't bind variables
in the patterns), so we could also use this name I think.  Also note
that we can't unite this macro with `if-let' (because it is about
non-nil-ness of values, while `pcase-if-let' is about pattern matching,
so a binding like (SYMBOL VALUE) has different semantics).


Thanks,

Michael.



reply via email to

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