开发者

Haskell Parse Paragraph and em element with Parsec

I'm using Text.ParserCombinators.Parsec and Text.XHtml to parse an input like this:

this is the beginning of the paragraph --this is an emphasized text-- and this is the end\n

And my output should be:

<p>this is the beginning of the paragraph <em>this is an emphasized text</em> and this is the end\n</p>

This code parses and returns an emphasized element


em = do{ 
      ;count 2 (char '-') ;
      ;s <- manyTill anyChar开发者_JS百科 (count 2 (char '-')) 
      ;return  (emphasize  << s)
     }

But I don't know how to get the paragraphs with emphasized items

Any ideas?

Thanks!!


This is a hack, but I think it does what you want:

list = (:[])
text = many (try em <|> (anyChar >>= return . list)) 
       >>= return . ("<p>"++) . (++"</p>") . concat

(Each non-emphasised character is return as its own string.)


Here's how it works:

At each char, first try to parse em. This starts with two dashes. Since em can fail after consuming a single dash, as in "a-b", you need to prefix it with try. If dashes are not allowed in the rest of the input, you don't need the try, but this is probably not the case. Otherwise, consume anyChar. But this is of type Char, not String, so it has to be wrapped in a list.

This returns a list of single-character strings with emphasised sections interleaved. But you want a single string surrounded by p tags, so you first concat, then add the start/end tags to the beginning/end. Then you return that value.

There is probably a way to rewrite this whole parser so that instead of anyChar you consume input until you see two dashes. But I'm not sure how to write that off the top of my head, so instead you get this hack, which is probably a lot less efficient.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜