Return from function inside if statement

All I'm trying to do is use the when statement to return a value :( I want functionality:

if(x)
    return y

And I'm trying to use:

(when (x) y)

But the when statement does not evaluate in such a way that it exits the function and returns y. He just happily moves on to the next line. Is there a way to do this without creating an extremely ugly if-else look? mzscheme / racket does not allow 1-armed ifs.

+4
source share
4 answers

You noted this with both Common Lisp and Racket, which are two completely different languages. If you use Racket or Scheme and want to return from the function earlier, you can do this using the continuation:

(define (my-function x y)
  (call-with-current-continuation
    (lambda (return)
      (when x (return y))
      ;; Rest of code not evaluated if X is true
      )))

, Racket, call-with-current-continuation call/cc, call-with-current-continuation - .

, cond. , , define, return:

(define-syntax define/return
   (syntax-rules ()
      ((_ (name . args) . body)
       (define (name . args)
         (capture-vars (return)
            (call/cc (lambda (return) . body)))))))

capture-vars, .

EDIT: Leppie define/return, , capture-vars:

(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: , return , define/return .

return , , :

(define/return (my-function x y)
    (when x (return y))
    ;;; more code...
)

, Common Lisp, . Common Lisp, (return y) block nil. nil, loop. nil return-from . , defun, , , :

(defun my-function (x y)
   (when x (return-from my-function y))
   ;;; more code
   )
+2

, " "; " " "else" ; . , , return . "if" "cond" , .

, " + ", , - " " , . ( ) .

; , !

EDIT: ant . , .

+8

A simple way to Racket:

(define (foo x)
  (let/ec return
    (when (= x 0)
       (return 'zero))
    'not-zero))

Here ec means continuation of continuation, which are cheaper than full continuation.

+7
source

Plain:

(and (x) y)

The problem is that when does not return a value. "and" does.

0
source

All Articles