Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell "Non-Exhaustive pattern exception"

the code below produces a "non-exhaustive pattern in function asd"

data Token = TokenPlus
            | TokenMinus
            | TokenMal
            | TokenGeteilt
            | TokenKlammerAuf
            | TokenKlammerZu
            | TokenInt Int
            deriving(Eq,Show)
asd (x:xs) = if x == '+' then (x, TokenPlus): (asd xs)
             else (x, TokenInt 1): (asd xs)

Let's say i wanted to catch this kind of error, i would use catch (asd "my_string") my_handler_function. Fine until here, but what Type is ":t 'non-exhaustive pattern' " made of ?

like image 940
kiltek Avatar asked May 22 '11 13:05

kiltek


1 Answers

Pattern match failure exceptions are of type PatternMatchFail. The base exceptions are all defined in Control.Exception.

Below is a use of Control.Exception.catch to catch a pattern match failure of the type you're talking about. Here, my operation and handler are both of type IO (), but you can make it anything you want - if the operatio is IO Int then the exception handler could return a default IO Int.

{-# LANGUAGE ScopedTypeVariables #-}
import Control.Exception as X

func = X.catch (print $ asd []) printErr

printErr :: SomeException -> IO ()
printErr e =  do
        case fromException e of
                Just (x:: PatternMatchFail) -> putStrLn "I caught the exception"
                                            >> print x
                nothing -> return ()

asd :: [Int] -> [Int]
asd (x:xs) = xs
like image 152
Thomas M. DuBuisson Avatar answered Sep 28 '22 05:09

Thomas M. DuBuisson