%name calc -- name of generated parsing function %tokentype { Token } -- type of accepted tokens -- calc :: [Token] -> t with t type of attribute of -- first rule %token '+' { PLUS } '*' { MULT } '(' { LPAREN } ')' { RPAREN } id { ID } num { NUM } %% -- as in yacc program : exp {} exp : exp '+' term {} | term {} term : term '*' factor {} | factor {} factor : id {} | num {} | '(' exp ')' {} { happyError :: [Token] -> a happyError ts = error $ "Parse error: " ++ show ts data Token = ID | NUM | PLUS | MULT | LPAREN | RPAREN | EOF deriving Show } ----------------------------------------------------------------------------- -- Generate parser with Happy by -- -- > happy exp.y -- -- Use the parser by loading the generated program `exp.hs` and -- evaluating, e.g., -- -- ghci> calc [ID,MULT,LPAREN,ID,PLUS,NUM,RPAREN] -- -----------------------------------------------------------------------------