On 04/08/2004, at 12:28 AM, MR K P SCHUPKE wrote:

f (case xs of (x:_) -> x; [] -> error "whoops") -- direct style

Yup, this is how I do it... I never use head!

I like to pass failures back up to the level where some kind of sensible
error message can be generated. In your example the error is no
better than with 'head' - the point is a Nothing can be 'caught'
outside of an IO monad.


I would suggest using the type system as I said earlier so:

toNonEmptyList :: [a] -> Maybe (NonEmpty a)
toNonEmptyList (a0:_) = Just (NonEmpty a)
toNonEmptyList _ = Nothing

Then redefine head:

head :: NonEmpty a -> a
head (NonEmpty (a0:_)) = a0

There's an interesting discussion going on at Lambda the Ultimate right now, about this very topic:


    http://lambda-the-ultimate.org/node/view/157#comment

There are plenty of noteworthy comments there, but one which quite nicely expresses my point of view is:

"Using Maybe for this is like saying - let's turn this partial function into a total one by lifting its range to include Nothing. It became total by obtaining permission to return something I have no use of. I do not say monads are not useful, or Maybe is not useful."

And, of course, there's the type wizardry post by Oleg:

    http://lambda-the-ultimate.org/node/view/157#comment-1043

"I'd like to point out that it is possible in Haskell98 to write non-trivial list-processing programs that are statically assured of never throwing a `null list' exception. That is, tail and head are guaranteed by the type system to be applied only to non-empty lists. Again, the guarantee is static, and it is available in Haskell98. Because of that guarantee, one may use implementations of head and tail that don't do any checks. Therefore, it is possible to achieve both safety and efficiency. Please see the second half of the following message:

    http://www.haskell.org/pipermail/haskell/2004-June/014271.html


-- % Andre Pang : trust.in.love.to.save

_______________________________________________
Haskell-Cafe mailing list
[EMAIL PROTECTED]
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to