haskell - Parsec: multiple possible options on one line -


all,

i'm trying write parser using parsec. goal able parse toy language.

right i'm struggling make parsec recognise 2 different possible options, example assignment , function invocation.

how 1 write "parsecode" function parse following:

x = 3 y = 4 plus(x,y) 

into:

(assignment "x" "3") (assignment "y" "4") (invocation "plus" ["x","y"]) 

thanks

edit:

** omitted brevity **

edit 2:

i built bit upon suggestions , have following problem running parse parsetester "bla" "{plus(3,4)\nmin(2,3)\nx=3\n" gives expected solution: right (body [invocation "plus",invocation "min",assignment "x" "3"]).

but running functionally (almost) equivalent parse parsebody "bla" "{plus(3,4)\nmin(2,3)\nx=3\n}" results in error:

left "bla" (line 4, column 2): unexpected end of input expecting white space or "=" 

i don't see problem. parser looking assignment should looking invocation? suggestions?

code:

data body = body [statement]     deriving (show)  data arguments = arguments [string]     deriving (show)  data statement = assignment string string                | invocation string     deriving (show)   parsebody :: parser body parsebody =     char '{'     statements <- many1 parsestatement     char '}'     return $ body statements  parsetester :: parser body parsetester =      char '{'     x <- many1 parsestatement     return $ body x  parsestatement :: parser statement parsestatement =         x <- try parseinvocation <|> parseassignment <?> "statement"         return x  parseinvocation :: parser statement parseinvocation =     spaces     name <- many1 (noneof " (")     spaces     char '('     spaces     bla <- many1 (noneof " )")     spaces     char ')'     char '\n'     return $ invocation name  parseassignment :: parser statement parseassignment =     spaces     var <- many1 (noneof " =")     spaces     char '=' <?> "equal in assignment"     spaces     value <- many1 (noneof "\n")     char '\n'     spaces     return $ assignment var value 

if need parse choices, use choice text.parsercombinators.parsec.combinator

choice [parseinvocation, parseassignmen] 

or simplier: try parseinvocation <|> try parseassignmen

p.s.

you use form text.parsercombinators.parsec.char:

many (oneof " ") == spaces  oneof " " == space 

Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

java.util.scanner - How to read and add only numbers to array from a text file -

iphone - Three second countdown in cocos2d -