Haskell - Parsec Parsing <p> element

I am using Text.ParserCombinators.Parsec and Text .XHtml to parse the input like this:

This is the first paragraph example \ n
with two lines \ n
\ n
And this is the second paragraph \ n

And my output should be:

<p>This is the first paragraph example\n with two lines\n</p> <p>And this is the second paragraph\n</p>

I have defined:


line= do{
        ;t<-manyTill (anyChar) newline
        ;return t
        }

paragraph = do{
        t<-many1 (line) 
        ;return ( p << t )
    }


      

But it returns:

<p>This is the first paragraph example\n with two lines\n\n And this is the second paragraph\n</p>

What's wrong? Any ideas?

Thanks!

+2


a source to share


2 answers


From the documentation for manyTill , it runs the first argument zero or more times, so two more newlines remain in effect and yours line

won't fail.

You are probably looking for something like many1Till

(for example many1

versus many

), but it doesn't seem to exist in the Parsec library, so you may need to collapse yourself: (warning: I don't have ghc on this machine, so this is completely untested)

many1Till p end = do
    first <- p
    rest  <- p `manyTill` end
    return (first : rest)

      



or a way:

many1Till p end = liftM2 (:) p (p `manyTill` end)

      

+4


a source


The combinator manyTill

matches zero or more occurrences of its first argument , according to the documentation, so it line

will happily accept an empty line, which means it many1 line

will consume everything up to the last newline in the file, rather than stopping on a double newline as you think.



+1


a source







All Articles