You could implement Common Lisp-style "return-from" with a custom
exception class:
public class BlockException extends Exception {
String name;
Object val;
public BlockException(String name, Object val) {
this.name = name;
this.val = val;
}
public String name() { return this.name; }
public Object value() { return this.val; }
}
(defmacro block [name & body]
`(try
(do ,@body)
(catch BlockException e
(if (= (.name e) (name ,name))
(.value e)
(throw e)))))
(defmacro return-from [name expr]
`(throw (BlockException. (name ,name) ,expr)))
Then use it:
(defn foo []
(block outside
(do-something
;; ...
(return-from outside 5)
;; ...
)))
Note sure exactly what you want, but you could try Lisp in Small Pieces
by Christian Queinnec. If I remember right he talks about exceptions in
terms of continuations.
Or you could just start reading up on continuations if you're not
familiar with them. Wikipedia has a call/cc page at
http://en.wikipedia.org/wiki/Call-with-current-continuation
Cheers,
Chris Dean
Heh, good catch :)
I've been switching between the two too much recently!
At least I didn't miss out the semicolons in the Java code ;)
Hi,
For the purposes of a DSL that I'm writing, it would be very
convenient to have a break/return statement that early exits from a
subroutine.
You can do something like this (PLT Scheme):
#lang scheme
(define (foo n)
(define (foo-helper return)
(if (> n 0)
(return n)
(* -1 n)))
(call/cc foo-helper))
(display (foo 10))
--
Chris Wilson <christophe...@gmail.com>