簡體   English   中英

如何使用 parsec 在 Haskell 中解析元組 (String,Int)

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

我想我已經設法將字符串解析為字符串並將字符串解析為 Int,但我還需要解析 (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)

您可以通過使用ApplicativeMonad接口從現有解析器進行組合來完成此操作。 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM