您好,我正在尝试转换此字符串
Blade Runner,Ridley Scott,1982,Amy,5,Bill,8,Ian,7,Kevin,9,Emma,4,Sam,7,Megan,4
到电影类型
type UserRatings = (String,Int)
type Film = (Title, Director, Year , [UserRatings])
来自包含25部电影的文字文件
这就是我试图做的事情
maybeReadTup :: String ->(String, Int)
maybeReadTup s = do
[(n, [c])] <- return $ reads s
return [(n, [c])]
parseLines :: [String] -> Film
parseLines list
| isInt(list !! 3) = (list !! 0,(list !! 1), read (list !! 2), maybeReadTup [ (list!!1,read (list !! 2) )])
isInt :: String ->Bool
isInt[] = True
isInt (x:xs)
| isNumber x = True && isInt xs
| otherwise = False
parseChars :: String -> String -> [String]
parseChars [] _ = []
parseChars (x:xs) stringCount
| x == ',' = [stringCount] ++ parseChars xs ""
| otherwise = (parseChars xs (stringCount ++ [x]))
parseAll :: [String] -> [Film]
parseAll [] = []
parseAll (x:xs) = parseLines (parseChars x "") : (parseAll xs)
但我错了类型可以有人请帮我解析这个UserRatings元组类型[(String,Int)]
?你能帮我理解parseLines是如何工作的吗?我是Haskell的新人
答案 0 :(得分:2)
以下是使用Text.Parsec
的解决方案:
import Text.Parsec
import Text.Parsec.String
type UserRatings = (String, Int)
type Title = String
type Director = String
type Year = Int
type Film = (Title, Director, Year, [UserRatings])
str :: Parser String
str = many1 (noneOf ",")
int :: Parser Int
int = read <$> many1 digit
tup :: Parser UserRatings
tup = do user <- str
_ <- oneOf ","
rating <- int
return (user, rating)
parser :: Parser Film
parser = do title <- str
_ <- oneOf ","
director <- str
_ <- oneOf ","
year <- int
_ <- oneOf ","
ratings <- sepBy tup (oneOf ",")
eof
return (title, director, year, ratings)
testString :: String
testString = "Blade Runner,Ridley Scott,1982,Amy,5,Bill,8,Ian,7,Kevin,9,Emma,4,Sam,7,Megan,4"
main :: IO ()
main = print $ runParser parser () "testString" testString