4 ms·
In Common Lisp the syntax for early return is so ugly (```(return-from function-name result)```) that I use it very rarely. In general, it seems that in the lan
by Grue3 9y ago
In Common Lisp the syntax for early return is so ugly (```(return-from function-name result)```) that I use it very rarely. In general, it seems that in the languages that use implicit return (Lisps, Haskell, Rust?) having an early return is discouraged by design.
- cesarb 9y agoEarly return is very common in Rust, either explicit or hidden within the try! macro (which recently became the ? operator, since it was used so often).
- kazinator 9y agoIn 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.
- junke 9y agoIn the rare case a return is needed, I prefer to put a nil block and a simple return, e.g. (return value). The nil block stands out and warns about the presence of a return. It also helps that all iteration constructs (do-*) have an implicit nil block.
- lispm 9y agoCommon Lisp does not use explicit returns much, since every expression returns one (or more) values. (lambda () (cond ((foo) x) ((bar) y) (t z))) Such a conditional like COND returns the value(s) of the last form in a clause -> here either the value of x, y or z.