|
From: | arthur miller |
Subject: | Sv: Is this a bug in while-let or do I missunderstand it? |
Date: | Mon, 11 Nov 2024 08:49:39 +0000 |
>Comprarison with a for loop is somewhat strained here. The while-let
I didn't meant to say that while-let was equivalent to that for-loop;
but tried to illustrate the expectaions. I hope it was clear from the rest.
>loop in Elisp is directly analogous to this C++ while loop:
>
> #include <iostream>
>
> int main() {
> while (bool run = true) {
> std::cout << "running\n";
> run = false;
> }
> std::cout << "out of loop\n";
> }
>
>and yes, it’s an infloop, too.
Actually didn't know we can introduce new variable in while declaration in
C++; in C it is verbotten:
~/repos/test $ gcc -o test test.c
test.c: In function 'main':
test.c:3:10: error: expected _expression_ before 'int'
3 | while (int i = 0) {
| ^~~
test.c:4:5: error: 'i' undeclared (first use in this function)
4 | i++;
| ^
test.c:4:5: note: each undeclared identifier is reported only once for each function it appears in
But that is just a regression (thought it as in C++ too :-)).
>What you’re looking for, though, seems to be a while loop with a
>break, which is expressed as a catch/throw in Elisp.
Yes, that is what I came to as well, if you check the rest of the
response to Eli as I suggested to mention catch/throw or cl-block/cl-return-from
in the docs.
Even better is named-let, which seems to be a general
version of while-let:
(defmacro while-test (spec &rest body)
(declare (indent defun))
(let* ((name (gensym "while-let-"))
(bindings (if (and (consp spec) (symbolp (car spec)))
(list spec)
spec)))
`(named-let ,name ,spec
,@body
(if (not (and ,@(mapcar #'car bindings)))
nil
(,name ,@(mapcar #'cadr bindings))))))
(pp (macroexpand-1
'(while-test ((run t))
(setf run nil))) (current-buffer))
(named-let while-let-141 ((run t))
(setf run nil) (if (not (and run)) nil (while-let-141 t)))
(pp (macroexpand-1
'(while-let ((run t))
(setf run nil))) (current-buffer))
(catch 'done140
(while t (if-let* ((run t)) (progn (setf run nil)) (throw 'done140 nil))))
As seen, they both expand to equivalent infinite loop.
For the illustration, named-let expands to a nice while loop itself:
(pp (macroexpand-all
'(while-test ((run t))
(setf run nil))) (current-buffer))
(let ((run t))
(let (retval)
(while
(let ((run run))
(progn
(setq run nil)
(if (not (and run)) nil (progn (setq run t) :recurse)))))
retval))
In my personal opinion while-let, while meant to be a "shortcut" to
certain style of expressions is a bit unfortunate name, since the "-let"
part of the name suggest establishing an environment around the body,
however that environment is read only which is not normal semantic of
let-bindings. In other words, the devil is in the details which perhaps was
not intentional?
|
[Prev in Thread] | Current Thread | [Next in Thread] |