emacs-devel
[Top][All Lists]
Advanced

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

Re: combining cond and let, to replace pcase.


From: Yuri Khan
Subject: Re: combining cond and let, to replace pcase.
Date: Tue, 28 Nov 2023 00:59:48 +0700

On Tue, 28 Nov 2023 at 00:10, Tomas Hlavaty <tom@logand.com> wrote:

> even better:>
>    (or
>      ;; Same as a clause in `cond',
>      (when CONDITION
>        do-this-if-CONDITION-then-exit...)
>      ;; Variables to bind, as in let
>      (let ((x foobar) y z (foo 5) a)
>        ;; Bindings continue in effect.
>        ...)
>      ...)

This reminds me of the times before Python 2.x had a ternary operator
‘X if CONDITION else Y’. Some FAQs said “you can use this trick:
‘CONDITION and X or Y’”, with a small print (sometimes skipped) “as
long as you guarantee that X evaluates to a truthy value”.

This is very error-prone. Novices can and will get bitten by this.

* ‘or’ evaluates its arguments in turn until one of them evaluates to non-nil.
* ‘when’ and ‘let’ evaluate to the last body form if any, or nil if none.

So, for the intended effect of exiting the ‘or’ when a branch is
taken, one has to make sure to terminate that branch with a truthy
expression:

    (or
      (when CONDITION
        do-this-possibly-returning-nil
        :break)
      (let (BINDINGS)
        do-something-else-possibly-returning-nil
        :break)
      …more branches…)

Also, a ‘cond’ or a ‘pcase’ form will return the result of the branch
taken, which can be nil. An ‘or’ form will return the result of the
branch taken, as long as it is not nil. A branch that returns nil will
result in evaluation of the next branch.



reply via email to

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