Parsec Haskell列表

问题描述 投票:1回答:1

我正在使用Text.ParserCombinators.ParsecText.XHtml来解析输入并获得HTML输出。

如果我的输入是:

    * First item, First level
    ** First item, Second level
    ** Second item, Second level
    * Second item, First level

我的输出应该是:

<ul><li>First item, First level <ul><li>First item, Second level </li><li>Second item, Second level </li></ul></li><li>Second item, First level</li></ul>

我写了这个,但显然不能递归地工作

list = do{ s <- many1 item;return (olist << s) }
item = do{ 
    (count 1 (char '*'))
    ;s <- manyTill anyChar newline
    ;return ( li <<  s)
  }

有任何想法吗?递归可以超过两个级别。 谢谢!

html parsing haskell parsec
1个回答
2
投票
list n = do first <- item n
            rest <- many $ try $ try (list (n+1)) <|> item n
            return $ ulist << (first : rest)

item n = do count n (char '*')
            s <- manyTill anyChar newline
            return $ li << s

现在,parse (list 1) "foo" "* a\n** a 1\n** a 2\n* b\n** b 1\n** b 2\n"将返回您要求的内容。

但请注意,嵌套列表本身应位于li中,因为它是有效的xhtml。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.