What is the Racket equivalent to 'return' for early exit?

1,483 views
Skip to first unread message

David Storrs

unread,
Nov 21, 2016, 12:37:19 PM11/21/16
to Racket Users
In Perl I would often write:

sub do_something {
    return unless ( some necessary condition is met );
    ... do the thing ...
}

In Racket I could wrap the rest of the procedure in an (if), but that adds an unnecessary level of indentation and feels clunky.  Is there a clean solution?

David Storrs

unread,
Nov 21, 2016, 12:41:13 PM11/21/16
to Racket Users
Edit:  I know I could also use call/cc and invoke the continuation to escape, but that still adds another layer of indentation for something that in the normal case won't be called.

It's not a big deal, but I was wondering about it.

George Neuner

unread,
Nov 21, 2016, 1:04:53 PM11/21/16
to racket users
In Racket, IF requires both alternatives be specified.   What's wrong with WHEN or UNLESS?

(define (do-something)
    (unless (some necessary condition is met)
      ... do the thing(s) ...)
)

George

Leif Andersen

unread,
Nov 21, 2016, 1:08:40 PM11/21/16
to David Storrs, Racket Users
Honestly, I personally like to use let/ec for this. I know it's still using continuations, but it is much more lightweight, both syntactically and in terms of run-time costs.

(define (do-something)
  (let/ec return
    (unless (some-condition)
      (return NO))

    (do-the-thing)))

Although honestly, with this pattern, I find that errors work better here, as they return early, and you can decide how they get handled with a with-handlers.

(define (do-something)
  (unless (some-condition)
    (error "NO"))
  (do-the-thing))

(with-handlers ([exn:fail? (lambda (e) (displayln "I returned early"))])
  (do-something))

But that is specifically because I prefer the workflow of catching errors, rather than always having to manually check the output of the function.... (I'm looking at you C...)

Hope that helps.


~Leif Andersen

--
You received this message because you are subscribed to the Google Groups "Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to racket-users+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

John Clements

unread,
Nov 21, 2016, 1:30:21 PM11/21/16
to David Storrs, Racket Users
Playing the role of irritating ideologue, it’s … me!

Yes, there’s let/ec, but my (limited) experience in industry suggests that reading functions that use ‘return’ liberally can be massively more difficult than one that uses ‘if’ or a related form. I would argue that the call/ec doesn’t actually make the code less clunky, it just hides the clunkiness, and makes the code harder to read, to boot. In the absence of return, you can generally easily deduce when control flow reaches a particular point (“we only get here if x is > 0 and the string is empty”). In the presence of return, this becomes “we only get here if x is > 0 and the string is empty and one of these 19 incomprehensible clauses didn’t trigger a return.”

I do think that call/ec makes sense in some circumstances; for instance, if you want to bail out of a deeply nested call, and the intervening calls are to functions that someone else wrote. But generally, I try to bite the bullet and use the if (or cond), on the theory that when I come to read my own code next year I’ll have some idea what it’s doing.

BTW: yes, my soapbox is huge. Huge!

John



Norman Gray

unread,
Nov 21, 2016, 1:33:04 PM11/21/16
to David Storrs, Racket Users

David, hello.

On 21 Nov 2016, at 17:37, David Storrs wrote:

> In Perl I would often write:
>
> sub do_something {
> return unless ( some necessary condition is met );
> ... do the thing ...
> }

One (not-really-an-)answer is that that's an intrinsically procedural
way of thinking about the function, which is therefore 'un-schemey', and
going against the grain. That seems a good answer if you attach a
particular value to idiomatic code, less so otherwise.

Another answer is to write something like

(or (and (necessary-condition-not-met) 'early-return-value)
;; other guards?...
(do-the-thing))

If (necessary-condition-not-met) is true, then this expression will
evaluate to 'early-return-value. That does add the extra level of
indentation you didn't want, but it may look quite natural (or hideous),
depending on the precise circumstances.

A third answer is, as you mentioned, calling with call/cc. Calling
explicitly with call/cc might indeed look untidy, but if this is
something you're using in a couple of places, then it's possible to wrap
it up prettily:

(require racket/stxparam)
(define-syntax-parameter check
(lambda (stx)
(raise-syntax-error (syntax-e stx) "can only be used inside
do-something-while-checking")))

(define-syntax-rule (do-something-while-checking form . forms)
(call/cc (lambda (*bail-out)
(define (check* ok?) ; ok? must be a thunk
(or (ok?) (*bail-out 'early-return-value)))
(syntax-parameterize ((check (make-rename-transformer
#'check*)))
form . forms))))

(define (necessary-condition-met) #f)
(do-something-while-checking
(check necessary-condition-met)
(printf "hello2~%"))

All the best,

Norman


--
Norman Gray : https://nxg.me.uk
SUPA School of Physics and Astronomy, University of Glasgow, UK

David Storrs

unread,
Nov 21, 2016, 1:35:04 PM11/21/16
to Leif Andersen, Racket Users
Okay, that makes sense.  Thanks, all.

David Storrs

unread,
Nov 21, 2016, 1:40:18 PM11/21/16
to John Clements, Racket Users
On Mon, Nov 21, 2016 at 10:30 AM, 'John Clements' via Racket Users <racket...@googlegroups.com> wrote:

> On Nov 21, 2016, at 09:37, David Storrs <david....@gmail.com> wrote:
>
> In Perl I would often write:
>
> sub do_something {
>     return unless ( some necessary condition is met );
>     ... do the thing ...
> }
>
> In Racket I could wrap the rest of the procedure in an (if), but that adds an unnecessary level of indentation and feels clunky.  Is there a clean solution?

Playing the role of irritating ideologue, it’s … me!

Yes, there’s let/ec, but my (limited) experience in industry suggests that reading functions that use ‘return’ liberally can be massively more difficult than one that uses ‘if’ or a related form.

I mostly agree with you.  I've found that functions should have at most two return points:  one at the top and one at the bottom.  The one at the top is just for checking preconditions before you start doing real work, the one at the bottom is the happy path result.
 
BTW: yes, my soapbox is huge. Huge!

I think you meant 'yuje'.  Or perhaps 'bigly'?  ;>

 

John

Norman Gray

unread,
Nov 21, 2016, 1:47:11 PM11/21/16
to David Storrs, Racket Users, Leif Andersen

Greetings.

On 21 Nov 2016, at 18:07, Leif Andersen wrote:

> (define (do-something)
> (unless (some-condition)
> (error "NO"))
> (do-the-thing))
>
> (with-handlers ([exn:fail? (lambda (e) (displayln "I returned
> early"))])
> (do-something))
>
> But that is specifically because I prefer the workflow of catching
> errors,
> rather than always having to manually check the output of the
> function....
> (I'm looking at you C...)

On reflection, I think this is a better answer than mine (and is
probably what I'd do in fact).

Apart from anything else, it means that (do-something) will only return
the type of thing it's supposed to return, and not anything that needs
checked. That would be still more important if you were using Typed
Racket.

Matthew Butterick

unread,
Nov 21, 2016, 1:59:46 PM11/21/16
to Leif Andersen, David Storrs, Racket Users

On Nov 21, 2016, at 9:37 AM, David Storrs <david....@gmail.com> wrote:

In Perl I would often write:

sub do_something {
    return unless ( some necessary condition is met );
    ... do the thing ...
}


On Nov 21, 2016, at 10:07 AM, Leif Andersen <le...@leifandersen.net> wrote:

Although honestly, with this pattern, I find that errors work better here, as they return early, and you can decide how they get handled with a with-handlers.

(define (do-something)
  (unless (some-condition)
    (error "NO"))
  (do-the-thing))

(with-handlers ([exn:fail? (lambda (e) (displayln "I returned early"))])
  (do-something))


I agree with Leif. I've learned this pattern from studying well-written Racket code. 

As I understand it, the policy idea is that when a called function doesn't do what it was asked to do, then the caller of the function — not the called function — should get to decide how serious a problem it is. So `error` / `with-handlers` is the best idiom.

I think of `return` as a way for a function to deliver its *expected result*, in the special circumstance where it has to bust out of a deeply nested block. IOW, `return` is not for error conditions. 

Ronie Uliana

unread,
Nov 22, 2016, 4:09:38 PM11/22/16
to Racket Users, david....@gmail.com
> To unsubscribe from this group and stop receiving emails from it, send an email to racket-users...@googlegroups.com.
>
> For more options, visit https://groups.google.com/d/optout.

Just notice I replied the digest email instead of post a response. :p

So, let me try again and sorry for the mess...

I made this macro for exactly for the same reason (it's basically Leif's answer) :)

https://gist.github.com/ruliana/80d7bb46225a22a3682711ca8bd11a1d

@JohnClements, I guess you have a point :) but I think David is mostly talking about what we call "Guard Clauses" (http://refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html), good or bad, they are a tool for simplifying code. But I agree, don't overdo it ^_^

Macro copied below for convenience (btw, sorry for the code, Racket is not my main programming language... yet)


#lang racket
(require racket/stxparam)

(provide return
define/guard)

(define-syntax-parameter return
(λ (stx)
(raise-syntax-error (syntax-e stx) "can only used inside \"define/guard\"")))

(define-syntax-rule (define/guard (name args ...) body0 body ...)
(define (name args ...)
(let/cc ret
(syntax-parameterize ([return (make-rename-transformer #'ret)])
body0
body ...))))

(define/guard (test2 a b)
(when (> a b) (return 456))
(displayln "hehehe")
123)
Reply all
Reply to author
Forward
0 new messages