首页 > 解决方案 > 如何在 Parsec 中返回多个解析的 ADT?

问题描述

我正在使用 Parsec 解析如下所示的文件:

## public_id

ANALOG-CLOCK

## name

Analog Wall Clock
Some more text...

## domain

Time measurement

More text here...

除了文件可以有可变数量的部分,其中每个部分以“##”行开头并且可能包含 0+ 内容行。

type Model = [Section]

data Section = Section String [String]
               deriving Show


headingLine :: Parser String
headingLine = do
  try (string "##")
  spaces
  title <- many1 (noneOf "\r\n")
  char '\n'
  return title


nonHeadingLine :: Parser String
nonHeadingLine = do
  try (noneOf "#")
  contents <- many1 (noneOf "\r\n")
  char '\n'
  return contents


section :: Parser Section
section = do
  title <- headingLine
  contentLines <- many1 nonHeadingLine
  spaces
  return $ Section title contentLines


model :: Parser Model
model = do
  s1 <- section
  s2 <- section
  s3 <- section
  return [s1, s2, s3]
  --return $ many1 section


main :: IO ()
main = do
  modelStr <- readFile "analog3.md"
  let result = do parse model "" modelStr
  case result of
    Left  err -> putStrLn $ "Error " ++ show err
    Right mdl -> putStrLn $ show mdl

我希望输出看起来像这样:

[Section "public_id" "ANALOG-CLOCK",Section "name" "Analog Wall Clock",Section "domain" "Time measurement"]

当我每个部分只有一个内容行并产生上述输出时,该代码有效。

我有两个问题:

1)当我每个部分有多个内容行时,代码不起作用,并且

2)当我使用return $ many1 section而不是return [s1, s2, s3],我得到一个类型错误“无法将类型'Text.Parsec.Prim.ParsecT String()Data.Functor.Identity.Identity [Section]'与'[Section]'匹配”。

如何让它处理多个内容行以及如何让它处理多个部分?谢谢。

标签: haskellparsec

解决方案


推荐阅读