[Haskell-cafe] Re: [Haskell-beginners] Just how unsafe is unsafe

Roel van Dijk vandijk.roel at gmail.com
Fri Feb 6 13:38:11 EST 2009

On Fri, Feb 6, 2009 at 5:22 PM, Alberto G. Corona <agocorona at gmail.com> wrote:
> then Data.List.head   Data.Maybe.fromMaybe etc are also unsafe?.
Yes, I consider them unsafe. Whenever I see those functions I know
that I have to look elsewhere to see if their preconditions hold. I
would have preferred that listToMaybe was called head and the existing
head called unsafeHead, partialHead or something else of that nature.

> unsafe does
> not mean "with possible errors". unsafeXXX convert something in the IO monad
> into something that is not. So it can potentially contaminate your pure
> code.
> But Data.List.head applied to a empty list  will interrupt the computation
> abruptly, so your code using head will either run side effect free or not
> run at all.
I guess what unsafe should mean is a matter of taste. Personally I
find correctness more important that pureness. An unsafe function will
crash your program if evaluated when its preconditions do not hold.
Whether that is because of impurity (segmentation fault?), a partial
pattern match or a direct error "bla" is not that important. It might
be important when determining why your program crashed, but the result
is still the same.

The ByteString library has a module called Data.ByteString.Unsafe with
plenty of unsafeXXX functions. The comment for unsafeHead for example
states: "A variety of head for non-empty ByteStrings. unsafeHead omits
the check for the empty case, so there is an obligation on the
programmer to provide a proof that the ByteString is non-empty." That
perfectly reflects my own philosophy on this issue.

More information about the Beginners mailing list