[Haskell-cafe] Re: Debugging partial functions by the rules

Robert Dockins robdockins at fastmail.fm
Wed Nov 15 16:50:32 EST 2006


On Wednesday 15 November 2006 15:53, John Hughes wrote:
> > From: Robert Dockins <robdockins at fastmail.fm>
> >
> > It seems to me that every possible use of a partial function has some
> > (possibly imagined) program invariant that prevents it from failing.
> > Otherwise it is downright wrong.  'head', 'fromJust' and friends
> > don't do anything to put that invariant in the program text.
>
> Well, not really. For example, I often write programs with command line
> arguments, that contain code of the form
>
>     do ...
>        [a,b] <- getArgs
>        ...
>
> Of course the pattern match is partial, but if it fails, then the standard
> error message is good enough.

I'd actually put this in a different category than 'partial function' (in what 
might be regarded as an abuse of termonology).  This is failure in a monad, 
and is something I personally use a lot.  Failure in IO just usually happens 
to have behavior very similar to calling 'error'.

I'll often write code in an arbitrary monad just to model partiality via 
the 'fail' function.  Sometimes, as here, I use partial pattern matches to do 
this implicitly.  Why is this better than 'error'?  Because it allows the 
code consumer decide how to deal with problems.  You can use runIdentity to 
convert 'fail' to 'error'.  You can run with runErrorT and recover the error 
message.  You can run it in a custom moand that has some other fancy error 
handling. etc, etc.


> This applies to "throw away" code, of course, and if I decide to keep the
> code then I sooner or later extend it to fix the partiality and give a more
> sensible error message. But it's still an advantage to be ABLE to write the
> more concise, but cruder version initially.

I'm not against partial pattern matching.  I think it's way better than using 
partial projection functions.

> This isn't a trivial point. We know that error handling code is a major
> part of software cost--it can even dominate the cost of the "correct case"
> code (by a large factor). Erlang's "program for the correct case" strategy,
> coupled with good fault tolerance mechanisms, is one reason for its
> commercial success--the cost of including error handling code *everywhere*
> is avoided. But this means accepting that code *may* very well fail--the
> failure is just going to be handled somewhere else.
>
> Haskell (or at least GHC) has good exception handling mechanisms too. We
> should be prepared to use them, and "let it fail" when things go wrong. The
> savings of doing so are too large to ignore.
>
> John

-- 
Rob Dockins

Talk softly and drive a Sherman tank.
Laugh hard, it's a long way to the bank.
       -- TMBG


More information about the Haskell-Cafe mailing list