Parsing Haskell Parsec项目计数

Parsing Haskell Parsec项目计数,parsing,haskell,functional-programming,parsec,Parsing,Haskell,Functional Programming,Parsec,我使用and来解析这样的输入: - 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> &

我使用and来解析这样的输入:

- 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

可以,但不包括编号。

有什么想法吗?


谢谢

您可能希望使用GenParser,将包含当前节号的状态作为一个反向顺序的列表,因此第1.2.3节将表示为[3,2,1],并且可能是列表的长度,以避免重复计数。差不多

data SectionState = SectionState {nums :: [Int], depth :: Int}
然后使解析器操作返回类型为GenParser Char SectionState a。您可以使用getState和setState访问解析器操作中的当前状态。当你得到一系列-在一行的开头,对它们进行计数,并将其与状态中的深度进行比较,适当地操作NUM列表,然后以相反的顺序发出NUM,我建议保持NUM的相反顺序,因为大多数时候你想要访问最不重要的项,因此,将其放在列表的首位既简单又高效

有关GenParser的详细信息,请参见Text.ParserCombinators.Parsec.Prim。更常见的解析器类型是您可能想说的类型Parser a=GenParser Char a

type MyParser a = GenParser Char SectionState a

在代码开头附近的某个地方。

您可能希望使用GenParser,将包含当前节号的状态作为一个列表,以相反的顺序使用,因此第1.2.3节将表示为[3,2,1],并且可能是列表的长度,以避免重复计数。差不多

data SectionState = SectionState {nums :: [Int], depth :: Int}
然后使解析器操作返回类型为GenParser Char SectionState a。您可以使用getState和setState访问解析器操作中的当前状态。当你得到一系列-在一行的开头,对它们进行计数,并将其与状态中的深度进行比较,适当地操作NUM列表,然后以相反的顺序发出NUM,我建议保持NUM的相反顺序,因为大多数时候你想要访问最不重要的项,因此,将其放在列表的首位既简单又高效

有关GenParser的详细信息,请参见Text.ParserCombinators.Parsec.Prim。更常见的解析器类型是您可能想说的类型Parser a=GenParser Char a

type MyParser a = GenParser Char SectionState a
在代码开头附近的某个地方