On Sat, May 8, 2010 at 12:15 AM, Ivan Lazar Miljenovic <ivan.miljeno...@gmail.com> wrote: > David Menendez <d...@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 <d...@zednenem.com> <http://www.eyrie.org/~zednenem/> _______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe