scheme - Returning from a function inside when statement -
all i'm trying use when statement return value :( want functionality of:
if(x) return y
and i'm trying use:
(when (x) y)
but when statement not evaluating in way exits function , return y. happily carries on next line. there way without making extremely ugly looking if-else block? mzscheme/racket not allow 1-armed ifs.
you tagged both common lisp , racket, 2 different languages. if you're using racket or scheme , want return function early, can using continuation:
(define (my-function x y) (call-with-current-continuation (lambda (return) (when x (return y)) ;; rest of code not evaluated if x true )))
in scheme implementations including racket, call-with-current-continuation
bound call/cc
, call-with-current-continuation
portable way use continuations.
the above uglier using cond
statement. if want rid of crap, can define macro creates alternate version of define
automatically creates continuation , binds return
:
(define-syntax define/return (syntax-rules () ((_ (name . args) . body) (define (name . args) (capture-vars (return) (call/cc (lambda (return) . body)))))))
this requires have capture-vars
macro, can find in this answer.
edit: leppie provided following implementation of define/return
simpler since doesn't require capture-vars
macro:
(define-syntax define/return (lambda (x) (syntax-case x () [(_ (name . args) . body) (with-syntax ([return (datum->syntax #'name 'return)]) #'(define (name . args) (call/cc (lambda (return) . body))))])))
edit 2: however, it's easy accidentally un-capture definition of return
doing way, if incorporate define/return
in macro.
then return
behave you'd expect , not syntactically repugnant:
(define/return (my-function x y) (when x (return y)) ;;; more code... )
however, if you're using common lisp, situation different. in common lisp, (return y)
compile when block
named nil
defined. forms implicitly define block named nil
, such loop
macro. without block named nil
, can still use return-from
return named block. if you're in function defined defun
, name of function name of block wraps function, work:
(defun my-function (x y) (when x (return-from my-function y)) ;;; more code )
Comments
Post a Comment