I think i already managed to parse strings to strings and strings to Ints but I also need to parse a (String,Int) type as userRatings is in order to read from a textFile correctly and I am using Parsec
This is the Parsing along with the import
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)
You can do this by composing from existing parsers using either the Applicative
or the Monad
interface. Parser
has instances of both.
Using Applicative
:
stringIntTuple :: Parser (String, Int)
stringIntTuple = (,) <$> yourStringParser <*> yourIntParser
Which is the same as the following:
stringIntTuple :: Parser (String, Int)
stringIntTuple = liftA2 (,) yourStringParser yourIntParser
Using Monad
:
stringIntTuple :: Parser (String, Int)
stringIntTuple =
do
theString <- yourStringParser
theInt <- yourIntParser
return (theString, theInt)
来源:https://stackoverflow.com/questions/35825148/how-to-parse-a-tuple-string-int-in-haskell-using-parsec