【问题标题】:Parsing a Tuple (String,Int) in Haskell [duplicate]在 Haskell 中解析元组(字符串,整数)[重复]
【发布时间】:2016-03-06 11:47:54
【问题描述】:

我需要将(String,Int) 类型解析为userRatings,以便正确读取textFile,并且我正在使用Parsec。这是解析和导入,我的stringInt tuple 函数有这个错误。

期待“Parsec (String, Int)”的另外两个参数 需要一个类型,但‘Parsec (String, Int)’有种类‘* -> * -> *’ 在“stringIntTuple”的类型签名中: stringIntTuple :: Parsec (String, Int)

    import Control.Monad
    import Control.Applicative((<*))
    import Text.Parsec
        ( Parsec, ParseError, parse        -- Types and parser
        , between, noneOf, sepBy, many1    -- Combinators
        , char, spaces, digit, newline     -- Simple parsers
        )
    -- Types
    type Title = String
    type Director = String
    type Year = Int
    type UserRatings = (String,Int) 
    type Film = (Title, Director, Year , [UserRatings])
    type Period = (Year, Year)
    type Database = [Film]


    -- 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
   stringIntTuple :: Parsec (String , Int)
   stringIntTuple = liftM2 (,) stringLit intLit

   film :: Parsec String u Film
   film = do

title <- stringLit
newline
director <- stringLit
newline
year <- intLit
newline
userRatings <- stringIntTuple
newline
return (title, director, year, userRatings)

【问题讨论】:

  • 请不要多次发布同一个问题。 Stack Overflow 具有吸引对现有问题的关注的机制。

标签: parsing haskell tuples monads parsec


【解决方案1】:

错误消息基本上是说您没有提供足够的类型参数。如果您将元组解析器的签名与其他签名进行比较,您就会明白原因:

stringLit :: Parsec String u String
listOfStrings :: Parsec String u [String]
stringIntTuple :: Parsec (String , Int)

在所有其他情况下,您提供三个类型参数,但对于 stringIntTuple,您只提供一个。

所以只需添加Stringu 作为前两个参数,就像您为其他参数所做的那样,它会起作用。

【讨论】:

  • 谢谢!虽然如此明显:P
猜你喜欢
  • 2011-08-01
  • 1970-01-01
  • 2014-09-27
  • 1970-01-01
  • 2021-04-23
  • 1970-01-01
  • 2019-08-27
  • 2023-03-15
  • 1970-01-01
相关资源
最近更新 更多