Parsecにちょっと触ってみる(3):エラーコンビネータ ()

エラーコンビネータ (<?>) はエラーの記述をパーサに追加します。
パーサが失敗したとき、入力を消費することなくエラーメッセージを返します。

import Text.ParserCombinators.Parsec

run :: Show a => Parser a -> String -> IO ()
run p input = case (parse p "" input) of
            Left err -> putStr "parse error at " >> print err
            Right x  -> print x

-- 区切りとして space または ',' 、文末として ".?!" のうちのどれか
sentence    :: Parser [String]
sentence    = do words <- sepBy1 word separator
                 oneOf ".?!"
                 return words
                
separator   :: Parser ()
separator   = skipMany1 (space <|> char ',') 
                        <?> "--space or ','--"  -- この文がエラー文字列になる。

word    :: Parser String
word    = many1 letter <?> "--word--"          -- この文がエラー文字列
>  run sentence "hi,di,hi."         --=> ["hi","di","hi"]

-- space か ','が来ると期待していたのに来ない・・・Orz       
>  run sentence "hi,ho"
parse error at (line 1, column 6):
unexpected end of input
expecting --space or ','--

-- アルファベットの連続が来ると期待していたのに来ない・・・Orz       
ghci>  run sentence "hi,123"
parse error at (line 1, column 4):
unexpected "1"
expecting space, "," or --word--