Vesa Karvonen
Posts: 116
Nickname: vkarvone
Registered: Jun, 2004
|
|
Re: Maybe there's a Java workaround
|
Posted: Sep 9, 2005 7:34 AM
|
|
> [...] interested in ML again, although I haven't decided > if it's better at this task.
Well, depends on what you mean by better. If you intend to ask whether it makes all resource management go away, then the answer is obviously no. What ML is considerably better at than Java is higher-order programming. Below is an example of the use of higher-order programming.
ML has exceptions (raise, handle), but the core language has nothing equivalent to Java's finally. However, using higher-order programming it is quite easy to implement it and the syntax remains quite readable. Below is one way to do it. Note that the below code is copy-pasted from my utility library. All of the definitions are useful on their own. You only need to write them once (or use a library).
datatype ('a, 'b) either = LEFT of 'a | RIGHT of 'b
fun either (fa, fb) = fn LEFT a => fa a | RIGHT b => fb b
fun eval th = LEFT (th ()) handle e => RIGHT e
fun throw exn = raise exn
fun past ef x = (ignore (ef ()) ; x)
fun try (th, fv, fe) = either (fv, fe) (eval th)
fun finally (th, ef) = try (th, past ef, throw o past ef)
You can now use finally like this:
finally (fn () =>
(print "Where?\n"
; raise Fail "Bye..."),
fn () =>
print "Here! Here!\n")
The above would look like this in Java:
try {
System.out.print("Where?\n");
throw Exception("Bye...")
} finally {
System.out.print("Here! Here!\n");
}
An interesting aspect of the ML implementation of finally is the use of the try-in-unless construct (of Benton and Kennedy [1]). The try function implements it. I wish you luck in trying to implement try-in-unless in Java in a convenient and reusable form. (Note that the handle construct of Standard ML is roughly equivalent to try-catch in Java (without finally). Java's try-catch has the same problems as ML's handle.)
Needless to say, higher-order programming allows you to codify resource management patterns.
[1] http://research.microsoft.com/~akenn/sml/ExceptionalSyntax.pdf
|
|