Within a LOOP
, you can use the Common Lisp (return)
form in any expression, which will cause the LOOP
form to immediately evaluate to the value given to return
.
LOOP
also has a return
clause which works almost identically, the only difference being that you don't surround it with parentheses. The clause is used within LOOP
's DSL, while the form is used within expressions.
(loop for x in list
do (if (listp x) ;; Non-barewords after DO are expressions
(return :x-has-a-list)))
;; Here, both the IF and the RETURN are clauses
(loop for x in list
if (listp x) return :x-has-a-list)
;; Evaluate the RETURN expression and assign it to X...
;; except RETURN jumps out of the loop before the assignment
;; happens.
(loop for x = (return :nothing-else-happens)
do (print :this-doesnt-print))
The thing after finally
must be an expression, so the (return)
form must be used and not the return
clause:
(loop for n from 1 to 100
when (evenp n) collect n into evens
else collect n into odds
finally return (values evens odds)) ;; ERROR!
(loop for n from 1 to 100
when (evenp n) collect n into evens
else collect n into odds
finally (return (values evens odds))) ;; Correct usage.