【发布时间】:2016-05-08 15:17:03
【问题描述】:
我正在通过解析文本文件中的行来学习使用 Parsec。我有以下内容:
import Text.Parsec (ParseError, parse)
import Text.Parsec.String (Parser)
import Text.Parsec.Char (anyChar, digit, char, oneOf)
import Control.Monad (void)
import qualified Text.Parsec.Combinator as C
data Action =
ActionA Int Int
| ActionB Int Int Int Int Int
| ActionC Int Int Int
deriving (Show)
parseWithEof :: Parser a -> String -> Either ParseError a
parseWithEof p = parse (p <* C.eof) ""
parseActionA :: Parser Action
parseActionA = do
char 'A'
void $ oneOf " "
a <- C.many1 digit
void $ oneOf " "
b <- C.many1 digit
return $ ActionA (read a) (read b)
parseActionB :: Parser Action
parseActionB = do
char 'B'
void $ oneOf " "
a <- C.many1 digit
void $ oneOf " "
b <- C.many1 digit
void $ oneOf " "
c <- C.many1 digit
void $ oneOf " "
d <- C.many1 digit
void $ oneOf " "
e <- C.many1 digit
return $ ActionB (read a) (read b) (read c) (read d) (read e)
parseActionC :: Parser Action
parseActionC = do
char 'C'
void $ oneOf " "
a <- C.many1 digit
void $ oneOf " "
b <- C.many1 digit
void $ oneOf " "
c <- C.many1 digit
return $ ActionC (read a) (read b) (read c)
我希望能够概括这些解析函数,因为我觉得它们是重复的。我不知道这是否可能,或者怎么可能。
我也想知道能不能有这样的功能:
parseAction :: String -> Either ParseError Action
parseAction input =
parseWithEof parseActionA input
<some operator|combinator> parseWithEof parseActionB input
<some operator|combinator> parseWithEof parseActionC input
所以当parseAction 接收到一个字符串作为参数时,它会尝试使用不同的解析器来解析它。如果没有解析器可以解析输入,我希望它返回 (Left ParseError),如果解析器成功解析输入,我希望它返回 (Right Action)。
有可能吗?
【问题讨论】: