On Thu, Apr 12, 2012 at 10:10 AM, rahulpilani <rahul.pil...@gmail.com> wrote: > Hi, > I am trying to use the parsatron library > (https://github.com/youngnh/parsatron) to parse a simple list of digits. I > am not able to get it to parse correctly, I was wondering what I was > missing.
Hi! Thanks for giving The Parsatron a whirl and I apologize for the late, late reply but here's what I'd try. When dealing with whitespace, I like to use a `tok` parser to handle the consuming of any leading whitespace. That way all other parsers I write can assume that they can immediately start parsing the thing itself, and not worry that there might be spaces or tabs on the front. Also, this allows for a single place to define what whitespace is. Something like: (defparser ws [] (either (char \space) (char \,))) (defparser tok [token-parser] (many (ws)) token-parser) The `array-item` parser I would define like this: (defparser array-item [] (let->> [digit-chars (many1 (digit))] (always (read-string (apply str digit-chars))))) Which brings us to the hard part, `arr`. Its tempting to write: (defparser arr [] (between (char LPAREN) (char RPAREN) (many (tok (array-item))))) and it'll even work for a number of inputs: (run (arr) "()") (run (arr) "(1)") (run (arr) "(1, 2, 3)") (run (arr) "( 1, 2, 3)") will all work, but if there is trailing whitespace after the last array item, the `(tok (array-item))` will consume it, and not find a number, but a RPAREN and you'll get an error: "Unexpected token ')' at line: 1 column: 11" (run (arr) "(1, 2, 3, )") ;; => RuntimeException The root of this problem is that The Parsatron doesn't implement backtracking by default (a decision that as more users ask questions, I'm rapidly rethinking), and instead relies on the programmer to implement backtracking using constructs like `lookahead` and `attempt`. I think you'll find that wrapping the `(tok (array-item))` in an `attempt` and then making the closing paren a `tok` will get you the list-parser you're looking for: (defparser arr [] (between (char LPAREN) (tok (char RPAREN)) (many (attempt (tok (array-item)))))) Cheers, Nate Young -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en