3 ms·
In Lisp other structures come into play that effectively give you early return in various situations, like for example cond. (cond (early-return-conditio
by kazinator 9y ago
In Lisp other structures come into play that effectively give you early return in various situations, like for example cond.
(cond
(early-return-condition early-value)
(second-early-condition early-value2)
...
(t final-else-value))
A cond as the last (or only) form of a body is basically an N-way switch toward multiple exit points, the ones appearing first being earlier.
In TXR Lisp I made block have dynamic scope, not only dynamic binding. You can do this:
(defun helper ()
(return-from master 42))
(defun master ()
(helper))
I.e. early return from nested helper functions, without a lot of added ceremony.
Speaking of this dialect, here is a function from its C internals, exhibiting a preference for an early return over else:
val flatten(val list)
{
if (list == nil)
return nil;
if (atom(list))
return cons(list, nil);
return mappend(func_n1(flatten), list);
}
If this were in the Lisp dialect instead of C, the same author would write it like this:
(defun flatten (list)
(cond
((null list) nil)
((atom list) (list list))
(t [mappend flatten list])))
and certainly not like this:
(defun flatten (list)
(when (null list)
(return-from flatten nil))
(when (atom list)
(return-from flatten (list list))
[mappend flatten list])
Even if the implicit block around a function body were the anonymous block, so that (return (list list)) could be used, this would still be eschewed as unidiomatic Lisp.