簡體   English   中英

Haskell Parsec項目計數

[英]Haskell Parsec items numeration

我正在使用Text.ParserCombinators.ParsecText.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

可以,但是不包括編號。

有任何想法嗎?

謝謝!

您可能想將GenParser的狀態以包含當前節號的狀態以相反的順序用作列表,因此第1.2.3節將表示為[3,2,1],並且可能將列表的長度表示為避免重復計數。 就像是

data SectionState = SectionState {nums :: [Int], depth :: Int}

然后,使您的解析器操作返回類型為“ GenParser Char SectionState a”。 您可以使用“ getState”和“ setState”在解析器操作中訪問當前狀態。 當您在一行的開頭獲得一系列“-”時,請對其進行計數,然后將其與狀態中的“深度”進行比較,適當地操作“數字”列表,然后以相反的順序發出“數字”(我建議保持數字以相反的順序進行操作,因為大多數時候您都希望訪問最不重要的項目,因此將其放在列表的頂部既容易又有效。

有關GenParser的詳細信息,請參見Text.ParserCombinators.Parsec.Prim。 更常見的解析器類型只是“類型解析器a = GenParser Char()a”,您可能想說

type MyParser a = GenParser Char SectionState a

在代碼開頭附近的某處。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM