Shammer's Philosophy

My private adversaria

How to break from loop in Common Lisp?

Description

I found the link in Stack Overflow discussed about this. The link is Return from a nested loop in Common Lisp - Stack Overflow. This is an continuous article of 【LISP繰り返し Hack 】do を展開してみる・その2 - Shammerism. This is a memo just in case.Here is a code example extracted from above link.

use block and return-from

(let (c s)
  (block nested-loops
    (do ((a 1 (1+ a))) ((= a 999))
      (do ((b a (1+ b))) ((= b 999))
        (setf c (sqrt (+ (expt a 2) (expt b 2)))
              s (+ a b c))
        (if (= s 1000)
            (return-from nested-loops (* a b c)))))))

use loop and named

(loop named outer for a from 1 below 1000 do
 (loop for b from a below 1000
    for c = (sqrt (+ (expt a 2) (expt b 2)))
    for s = (+ a b c)
    if (= s 1000) do (return-from outer (* a b c))))