Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning from a function inside when statement

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

if(x)
    return y

And I'm trying to use:

(when (x) y)

But the when statement is not evaluating in a way that exits the function and return y. It just happily carries on to the next line. Is there a way to do this without making an extremely ugly looking if-else block? mzscheme/racket does not allow 1-armed ifs.

like image 304
Roguebantha Avatar asked Apr 29 '15 03:04

Roguebantha


People also ask

Can you put a return inside and if statement?

Yes, you can use the nested usage of IF. Example: IF( Condition1, True,IF(Condition2,True).

How do you return a value from an if statement?

Use the IF function, one of the logical functions, to return one value if a condition is true and another value if it's false. For example: =IF(A2>B2,"Over Budget","OK") =IF(A2=B2,B4-A4,"")

Can we write return in if statement?

No, both values aren't going to be returned. A return statement stops the execution of the method right there, and returns its value. In fact, if there is code after a return that the compiler knows it won't reach because of the return , it will complain.

How do you return inside a function?

To return a value from a function, you must include a return statement, followed by the value to be returned, before the function's end statement. If you do not include a return statement or if you do not specify a value after the keyword return, the value returned by the function is unpredictable.


1 Answers

A simple way in Racket:

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

Here ec stands for escape continuations, which are cheaper than full continuations.

like image 172
soegaard Avatar answered Sep 18 '22 18:09

soegaard