【发布时间】:2016-06-19 21:44:23
【问题描述】:
我想我已经设法将字符串解析为字符串并将字符串解析为 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)
【问题讨论】:
-
使您的代码自包含(参见stackoverflow.com/help/mcve);特别是,添加您的导入。
-
你需要导入这个才能看到问题 import Text.Parsec ( Parsec, ParseError, parse -- Types and parser , between, noneOf, sepBy, many1 -- Combinators , char, spaces, digit, newline -- 简单的解析器)