elm-community / parser-combinators

A parser combinator library for Elm.
http://package.elm-lang.org/packages/elm-community/parser-combinators/latest
BSD 3-Clause "New" or "Revised" License
104 stars 13 forks source link

add manyTill #4

Closed toburger closed 8 years ago

toburger commented 8 years ago

Hi Bogdan,

I'm using your parser combinator lib for parsing XML responses (from a legacy web service). I love your lib so far, however I was missing one specific combinator, available in other parser combinator libs (Haskell, F#) called manyTill. It allows to process one parser till another parser matches.

This combinator is especially useful for parsing comments like for instance:

 (string "<!--" *> manyTill anyChar (string "-->"))

I'm not an expert in writing combinators (nor in elm) so I'm sure there exists a better implementation for this function.

Cheers Tobias

Bogdanp commented 8 years ago

Thanks for contributing! This looks good but I think a few things could be improved:

So how about this instead:

manyTill : Parser res -> Parser end -> Parser (List res)
manyTill p end =
  let
    accumulate acc cx =
      case app end cx of
        (Fail err, cx) ->
          case app p cx of
            (Done res, cx') ->
              accumulate (res :: acc) cx'

            _ ->
              (Fail err, cx)

        (Done _, cx') ->
          (Done (List.reverse acc), cx')
  in
    Parser <| accumulate []
toburger commented 8 years ago

Go ahead! I knew my code could be improved! thx! :)

Bogdanp commented 8 years ago

Alright, it's in 1.2.0 :). Thanks again for contributing!