Re: Break Statements similar to C or C++
- From: Raffael Cavallaro <raffaelcavallaro@pas-d'espam-s'il-vous-plait-mac.com>
- Date: Thu, 31 May 2007 16:04:04 -0400
On 2007-05-31 07:55:47 -0400, grue@xxxxxxx (Timofei Shatrov) said:
Also there is loop-finish macro, which is often preferable to above-mentioned
methods.
Yes, but one should be aware that loop-finish is unlike break in that loop-finish causes execution to continue with the loop epilogue - the parts after finally or the automatic return of any accumulated values - while break in c and the methods shown above in lisp will cause control flow to exit the loop entirely - sbcl for example will delete the epilogue in such cases as unreachable code.
For example, this is probably not what one wants:
CL-USER> (loop named foo
for i = 0 then (random 100)
collect i ;;; you'll never see this accumulated list
when (> i 76) do (return-from foo i))
; in: LAMBDA NIL
; (RETURN-FROM FOO (SB-LOOP::LOOP-COLLECT-ANSWER #:LOOP-LIST-HEAD-1775))
; ; note: deleting unreachable code
; ; compilation unit finished
; printed 1 note
92
but this is:
CL-USER> (loop for i = 0 then (random 100)
collect i
when (> i 76) do (loop-finish))
(0 47 32 52 95)
and this could be too:
CL-USER> (loop named foo
for i = (random 100)
collect i
when (= i 91)
do (return-from foo 'exceptional-number-encountered)
when (< i 10)
do (loop-finish))
(65 54 37 50 38 93 12 99 94 83 95 77 39 62 82 51 62 88 2)
CL-USER> (loop named foo
for i = (random 100)
collect i
when (= i 91)
do (return-from foo 'exceptional-number-encountered)
when (< i 10)
do (loop-finish))
EXCEPTIONAL-NUMBER-ENCOUNTERED
loop-finish is more like a 'go' to a label placed at the start of the loop epilogue rather than a simple break, so one should use loop-finish when one *always* wants the loop epilogue to execute, and one should use one of the other techniques when one wants exceptional situations to terminate the loop a-la c's break - without executing any loop epilogue.
.
- References:
- Break Statements similar to C or C++
- From: gokul.mano@xxxxxxxxx
- Re: Break Statements similar to C or C++
- From: Raffael Cavallaro
- Re: Break Statements similar to C or C++
- From: Timofei Shatrov
- Break Statements similar to C or C++
- Prev by Date: Re: garnet: still no success
- Next by Date: Re: Break Statements similar to C or C++
- Previous by thread: Re: Break Statements similar to C or C++
- Next by thread: Question about loop
- Index(es):
Relevant Pages
|