From: Ken A. <kan...@bb...> - 2002-04-23 20:29:19
|
At 02:59 PM 4/23/2002, you wrote: >is there a Scheme equivalent to CL's (return) ? > >I have loops I want to terminate early (i.e., at a certain condition being >met), where I'd prefer for simplicity to use DOLIST rather than DO... > >is that appropriate in scheme? Good question. I keep meaning to write a tutorial for Scheme for Lispers. The general way to return something is with call/cc (call-with-current-continuation) > (define (the-first p xs) (call/cc (lambda (return) (for-each* (lambda (x) (if (p x) (return x))) xs)))) {jsint.Closure the-first[2] (p xs)} > (the-first odd? #(2 3 4 5 6)) 3 > Here's a version of dolist that lets you use return: (define-macro (dolist iters . body) ;; Like Common Lisp's (dolist). (let ((var (car iters)) (items (cadr iters)) (result (or (and (pair? (cddr iters)) (caddr iters)) '()))) `(call/cc (lambda (return) (let <loop> ((.items. ,items)) (if (null? .items.) ,result (let ((,var (car .items.))) ,@body (<loop> (cdr .items.))))))))) > {jsint.Macro ??[1,n] (iters . body)} > (dolist (x '(2 3 4 5 6)) (if (odd? x) (return x))) 3 > |