Haskell Parsec 项目计数
我正在使用 文本。 ParserCombinators.Parsec 和 Text.XHtml 来解析这样的输入:
- First type A\n -- First type B\n - Second type A\n -- First type B\n --Second type B\n
我的输出应该是:
<h1>1 First type A\n</h1>
<h2>1.1 First type B\n</h2>
<h1>2 Second type A\n</h2>
<h2>2.1 First type B\n</h2>
<h2>2.2 Second type B\n</h2>
我已经到了这一部分,但我无法进一步:
title1= do{
;(count 1 (char '-'))
;s <- many1 anyChar newline
;return (h1 << s)
}
title2= do{
;(count 2 (char '--'))
;s <- many1 anyChar newline
;return (h1 << s)
}
text=do {
;many (choice [try(title1),try(title2)])
}
main :: IO ()
main = do t putStr "Error: " >> print err
Right x -> putStrLn $ prettyHtml x
这是可以的,但它不包括编号。
有什么想法吗?
谢谢!
I'm using Text.ParserCombinators.Parsec and Text.XHtml to parse an input like this:
- First type A\n -- First type B\n - Second type A\n -- First type B\n --Second type B\n
And my output should be:
<h1>1 First type A\n</h1>
<h2>1.1 First type B\n</h2>
<h1>2 Second type A\n</h2>
<h2>2.1 First type B\n</h2>
<h2>2.2 Second type B\n</h2>
I have come to this part, but I cannot get any further:
title1= do{
;(count 1 (char '-'))
;s <- many1 anyChar newline
;return (h1 << s)
}
title2= do{
;(count 2 (char '--'))
;s <- many1 anyChar newline
;return (h1 << s)
}
text=do {
;many (choice [try(title1),try(title2)])
}
main :: IO ()
main = do t putStr "Error: " >> print err
Right x -> putStrLn $ prettyHtml x
This is ok, but it does not include the numbering.
Any ideas?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能希望将 GenParser 与包含当前节号的状态一起使用作为相反顺序的列表,因此节 1.2.3 将表示为 [3,2,1],并且可能是列表的长度以避免重复计数。类似于
然后使您的解析器操作返回类型为“GenParser Char SectionState a”。您可以使用“getState”和“setState”访问解析器操作中的当前状态。当您在行开头得到一系列“-”时,对它们进行计数并将其与状态中的“深度”进行比较,适当地操作“nums”列表,然后以相反的顺序发出“nums”(我建议保留 nums以相反的顺序,因为大多数时候您想要访问最不重要的项目,因此将其放在列表的头部既更容易又更有效)。
有关 GenParser 的详细信息,请参阅 Text.ParserCombinators.Parsec.Prim。更常见的解析器类型只是“type Parser a = GenParser Char () a”您可能想说
在代码开头附近的某个地方。
You probably want to use GenParser with a state containing the current section numbers as a list in reverse order, so section 1.2.3 will be represented as [3,2,1], and maybe the length of the list to avoid repeatedly counting it. Something like
Then make your parser actions return type be "GenParser Char SectionState a". You can access the current state in your parser actions using "getState" and "setState". When you get a series of "-" at the start of a line count them and compare it with "depth" in the state, manipulate the "nums" list appropriately, and then emit "nums" in reverse order (I suggest keeping nums in reverse order because most of the time you want to access the least significant item, so putting it at the head of the list is both easier and more efficient).
See Text.ParserCombinators.Parsec.Prim for details of GenParser. The more usual Parser type is just "type Parser a = GenParser Char () a" You probably want to say
somewhere near the start of your code.