The less-familiar parts of Lisp for beginners — block

Continuing the series, another Lisp directive that newcomers arriving from C++ might not immediately encounter is block.  This is a simple flow-control statement which can almost be emulated using a goto in C++.

What block does is to create a named collection of statements, such that flow can immediately exit the block when return-from is used.  In C++, you could imagine putting a label immediately after the last statement in the Lisp block, and then using goto to branch to that label.  This is not quite an exact parallel because a Lisp block can return a value, while that concept doesn’t apply in C++.

In Lisp, a block that exits normally returns the result of its last statement.  In the event of a branch with return-from, an optional second argument is the return value of the block, otherwise the block returns nil.

Note that the Lisp return statement does not take a name as an argument, and returns from the innermost enclosing unnamed (nil) block, whether named or not.  This might be a block you created with the block directive, or it might be an implicit block surrounding one of the looping constructs, so for safety you’re encouraged to use named blocks and return-from when that is appropriate.  When using a looping construct like do, dolist, or dotimes, a bare return reads like a break in C++.

2 thoughts on “The less-familiar parts of Lisp for beginners — block

  1. Hello.
    You say:

    “Note that the Lisp return statement does not take a name as an argument, and returns from the innermost enclosing block, whether named or not.”

    but i think “return” only returns from the innermost “nil” block, for instance:
    CL-USER> (block nil
    (block innermost
    (print “innermost here.”)
    (return ‘done)
    )
    (print “done with block nil”)
    )

    “innermost here.”
    DONE

    If “return” where returning from the innermost block, the “done with block nil” message should be printed, and it isn’t, because it is returning from the nil block, not the innermost one. In my implementation “(return ‘done)” expands to “(return-from nil ‘done)” (SBCL 1.1.14)

    http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/mac_return.html#return

    I’m still a bit wet behind the ears regarding common lisp, so i might be getting things wrong.

    Oh, by the way, these series of articles are awesome! keep up the good work!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

反垃圾邮件 / Anti-spam question * Time limit is exhausted. Please reload CAPTCHA.