Thursday, October 30, 2008

Maybe vs. exception vs. failure thunk in Scheme

It's pretty easy to switch back and forth between representing a function with a "maybe" result type as:
  1. returning X or #f;
  2. returning X or raising an exception; or
  3. returning X and taking a failure thunk
In Scheme, sometimes X might include the value #f. In that case I think representation #3 is the best one, since raising an exception is clunky. You can also combine #2 and #3 and take an optional thunk that by default raises an exception.

This is one case where true unions do cause some problems, so maybe I should have tempered my earlier enthusiasm a little. Still, it's not insurmountable, and this cost needs to be weighed against the price of strictly disjoint unions.

1 comment:

Ben Simon said...

I agree with you, solution #3 is very scheme like.

For some functions, I actually like using CPS and passing in both a success continuation and a failure continuation. What's nice here is that the failure case is treated by the programmer as just as likely as the success case.

You don't end up with the classic case of using a return value and having a lazy programmer not perform checks on it.

It also allows you to have three or more paths expressed just as easily as a success-or-fail type scenario.

Of course, the problem with this approach is that it can quickly get out of hand, and you end up writing your entire app in CPS.