There are many ways to handle errors in Haskell.
The Maybe method is the simplest but it also comes with a little overhead, since you always have to unpack the Maybe a value return, and finally I often end up by doing something like :
maybe (error "Unexpected Nothing") id someSafeFunction
when you absolutely do not expect your code to return a Nothing here.
There's also the possibility to handle errors through a monad (e.g. using Maybe as a monad), but all your functions must be designed as such.
I don't how the Error monad could be used there, I've never studied it...
I think using explicit exceptions is better in that case :
secondElement (_:x:_) = x
secondElement _ = error "secondElement: length < 2"
The major problem with exceptions is that Haskell has -- afaik -- no notion of traceback (to know exactly where the exception was raised). For instance, here, if secondElement is called more than once in your code, if you get the exception, you won't be immediately able to tell which part of the code raised it.
Ivan Miljenovic <ivan.miljenovic@gmail.com> disse:
> On 3 May 2010 14:17, aditya siram <aditya.siram@gmail.com> wrote:I don't think that safeSecondElement is worse than secondElement. I think it's
>> I'm a little confused about this too. I've seen many functions defined like:
>> f x = (\s -> ...)
>> which is a partial function because it returns a function and is the same as:
>> f x s = ...
>
> No, that's a partially applied function.
>
> A partial function is one such as:
>
> secondElement (_:x:_) = x
>
> Note that it is only defined for lists with at least two elements, for
> any other list (i.e. singleton or empty) it will throw an error;
> -fwarn-incomplete-patterns (which is included in -Wall) tells you
> about these.
>
> You can also argue that functions such as head are partial, as they
> explicitly throw an error if the input data isn't correct.
>
> Partial functions are bad because if you accidentally use one the
> wrong way, your entire program crashes in a flaming wreck. It's much
> better to do something like this:
>
> safeSecondElement (_:x:_) = Just x
> safeSecondElement _ = Nothing
>
> This will work with all possible input types.
better for the program to crash right away when you try to do something that
doesn't make sense.
Getting the secondElement of a list with one or less elements doesn't make
sense, so you are definetely doing something wrong if you expected the list to
have two elements, but it doesn't. It's best that the program crashes there,
than propagate the error and crash somewhere else or, worse, not crash at all
and give a wrong answer.
_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe