【问题标题】:How to parse a Tuple (String,Int) in Haskell using parsec如何使用 parsec 在 Haskell 中解析元组(String,Int)
【发布时间】: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 -- 简单的解析器)

标签: file haskell io parsec


【解决方案1】:

您可以通过使用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)

【讨论】:

  • 我仍然收到此错误 Expecting more arguments to 'Parsec (String, Int)' Expected a type, but 'Parsec (String, Int)' has kind '* -> * -> * ' 在 'stringIntTuple' 的类型签名中: stringIntTuple :: Parsec (String, Int)
  • 那是因为您使用的是Parsec 而不是Parser
  • 当我将所有内容更改为 Parser 时,它说不在范围内 不在范围内:类型构造函数或类'Parser' 也许你的意思是'Parsec'(从 Text.Parsec 导入)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多