ollef / Earley

Parsing all context-free grammars using Earley's algorithm in Haskell.
BSD 3-Clause "New" or "Revised" License
361 stars 24 forks source link

Roman numerals example #30

Closed kenkku closed 7 years ago

kenkku commented 7 years ago

Thanks for the interesting package, I played around with it for a while and came up with a parser for Roman numerals. I thought a larger example might be useful, so here's one :)

Any suggestions on improving the example are also appreciated.

ollef commented 7 years ago

Hey, and thanks! That's a really good idea.

As an example I think it would benefit from not defining too many new combinators (i.e. being a bit more simple minded), and perhaps just returning the decimal result directly.

I'd imagine you could get something like the following going (I just had a look at the YACC grammar at http://www.cs.bath.ac.uk/~occ/comp0029/roman_numerals.shtml):

romanNumeralsGrammar :: Grammar r (Prod r String Char Int)
romanNumeralsGrammar = mdo
  let s str = list str <?> str

  thousands <- rule
    $ pure 0
    <|> (1000 +) <$ s "M" <*> thousands

  hundreds <- rule
    $ le300
    <|> 400 <$ s "CD"
    <|> 900 <$ s "CM"
    <|> (500 +) <$ s "D" <*> le300
...

and so on. Do you agree?

kenkku commented 7 years ago

Thanks for the suggestion! I rewrote the example based on the grammar you linked, it looks a lot more tidy now and it's shorter as well. I also added the example as an executable to the .cabal file. Tell me what you think!

ollef commented 7 years ago

That looks great! Many thanks!