haskell - 如何在 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]'匹配”。
如何让它处理多个内容行以及如何让它处理多个部分?谢谢。
解决方案
推荐阅读
- python - python dataframe .duplicated 返回相同值的多次出现
- javascript - 谷歌云函数python中的CORS错误chrome扩展
- gradle - Gradle Checkstyle 插件与 google checkstyle 的兼容性
- flutter - 颤振:list.sort() 或比较器功能不起作用
- python - 在 HyperNetX 中查找节点的所有超边
- android - 生成签名 Apk 时出现问题
- javascript - VSCode 编写脚本为 React Native 项目运行多行
- android - 当我打开我的颤振应用程序时,它总是显示登录屏幕几秒钟,即使我已经在上次会话中登录。在那个主页之后?
- c# - C# 来自在运行时创建不同实例的单例模式类的意外输出
- python - 用数据框中的索引替换每个非零值