我认为我已经设法将字符串解析为字符串和字符串到Ints但我还需要解析(String,Int)类型,因为userRatings是为了正确读取textFile而我正在使用Parsec
这是解析和导入
import Text.Parsec
( Parsec, ParseError, parse -- Types and parser
, between, noneOf, sepBy, many1 -- Combinators
, char, spaces, digit, newline -- Simple parsers
)
-- Parse a string to a string
stringLit :: Parsec String u String
stringLit = between (char '"') (char '"') $ many1 $ noneOf "\"\n"
-- Parse a string to a list of strings
listOfStrings :: Parsec String u [String]
listOfStrings = stringLit `sepBy` (char ',' >> spaces)
-- Parse a string to an int
intLit :: Parsec String u Int
intLit = fmap read $ many1 digit
-- Or `read <$> many1 digit` with Control.Applicative
film :: Parsec String u Film
film = do
-- alternatively `title <- stringLit <* newline` with Control.Applicative
title <- stringLit
newline
director <- stringLit
newline
year <- intLit
newline
userRatings <- listOfStrings
newline
return (title, director, year, userRatings)
答案 0 :(得分:1)
您可以通过使用Applicative
或Monad
接口从现有解析器进行合成来完成此操作。 Parser
包含两者的实例。
使用Applicative
:
stringIntTuple :: Parser (String, Int)
stringIntTuple = (,) <$> yourStringParser <*> yourIntParser
与以下内容相同:
stringIntTuple :: Parser (String, Int)
stringIntTuple = liftA2 (,) yourStringParser yourIntParser
使用Monad
:
stringIntTuple :: Parser (String, Int)
stringIntTuple =
do
theString <- yourStringParser
theInt <- yourIntParser
return (theString, theInt)