[Haskell-cafe] IO (Either a Error) question

David Menendez dave at zednenem.com
Sat May 8 00:56:12 EDT 2010


On Sat, May 8, 2010 at 12:15 AM, Ivan Lazar Miljenovic
<ivan.miljenovic at gmail.com> wrote:
> David Menendez <dave at zednenem.com> writes:
>>
>> I wonder how often people rely on the use of fail in pattern matching.
>> Could we get by without fail or unfailable patterns?
>>
>> ensureCons :: MonadPlus m => [a] -> m [a]
>> ensureCons x@(_:_) = return x
>> ensureCons _ = mzero
>>
>> do ...
>>     x:xs <- ensureCons $ some_compuation
>>
>> This is more flexible than the current situation (you can easily adapt
>> it to throw custom exceptions in ErrorT), but gets cumbersome when
>> you're doing nested patterns. Also, it does the match twice, but
>> presumably the optimizer can be improved to catch that if the idiom
>> became popular.
>
> Well, any time you have a do-block like this you're using failable
> patterns:
>
> maybeAdd       :: Maybe Int -> Maybe Int -> Maybe Int
> maybeAdd mx my = do x <- mx
>                    y <- my
>                    return $ x + y

This is true in the sense that the translation for the do syntax in
the Haskell report uses fail.

do { p <- e; stmts } =
    let ok p = do { stmts }
        ok _ = fail "..."
    in e >>= ok

However, it's also true that the fails introduced by the translation
of maybeAdd will never be invoked, since the two patterns are
irrefutable. That is, maybeAdd would work exactly the same if the do
syntax translation were changed to read:

do { p <- e; stmts } = e >>= \p -> do { stmts }


This would not be the case if refutable patterns were used.

viewM l = do { x:xs <- return l; return (x,xs) }

-- 
Dave Menendez <dave at zednenem.com>
<http://www.eyrie.org/~zednenem/>


More information about the Haskell-Cafe mailing list