How to parse a Tuple (String,Int) in Haskell using parsec

核能气质少年 提交于 2019-12-31 07:31:45

问题


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)

回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!