[Haskell-cafe] exceptions vs. Either

MR K P SCHUPKE k.schupke at imperial.ac.uk
Tue Aug 3 15:44:48 EDT 2004

>As for head, I think it's fine that it throws an error because it is
>specified to be defined for only non-empty lists.

But surely it is better to encode this fact in the type system by
useing a separate type for non-empty lists.

>Argh, no!  Violating the precondition of head is a bug in the caller,
>I want it to crash,

Again by encoding this at the type level the compiler can guarantee that
that it is not going to crash or return a compile time error... also by
forcing the programmer to deliberatly cast to a non-empty list you
make explicit the 'non-emptyness'... also the type signature of head
contains the 'contract' that the list must be non empty.

>A mechanism for a function to report the caller site would obliviate
>the need for all this ugliness

Unfortunately the cost of this is prohabative as the call stack
would have to contain backtrace information. Also due to lazy
evaluation the 'call site' may not be what you expect.

I guess we just have to disagree I find very little cause to use head.

Here's what John Meacham had to say:

Note that pattern matching rather than deconstruction functions have a
number of benefits, not just relating to error messages, consider two
functions which use the head of their argument.

f xs =3D ... head xs ...=20
g (x:_) =3D ... x ...

now, g is superior to f in several ways,=20

1) the error message generated if the pattern fails will have the file
name, line number and name of function

2) everything but the head of xs may be garbage collected right away
since there is no reference to the rest of the list!  This can cure some
nasty space leaks and is vital in certain cases.=20

3) even the simplest compiler will realize g is stirct in its first
argument and take advantage of the numerous optimizations that entails.=20

A good compiler may figure out 2 and 3 with f, but it can't always, and w=
take the chance it won't? All of these benefits apply to deconstructing
more complicated types too, so using pattern matching for deconstruction
is just a good habit to get into.


More information about the Haskell-Cafe mailing list