parsing - Recursive Descent Parser using Python and PLY -
i apologize basic question but, i'm struggling here. need make recursive descent parser. i'm working in python , using ply. grammar follows:
< list > → (< sequence >) | ()
< sequence > → < listelement > , < sequence > | < listelement >
< listelement > → < list > | number
would this? way off? end goal read list data structure , print out.
def p_list(p) 'list : "("sequence")" | "("")"' def p_sequence(p) 'sequence : list_el","sequence | list_el' def p_list_el(p) 'list_el : list | number'
if wondering full solution i'll post shortly.
this how i'd it:
tokens = ("lbracket", "rbracket", "integer", "float", "comma") # can add other tokens t_lbracket = r'\(' t_rbracket = r'\)' t_integer = r'\d+' t_float = r'\d+\.\d+' t_comma = r',' def p_list(p): """list : lbracket sequence rbracket | lbracket rbracket""" if len(p) == 4: p[0] = p[2] else: p[0] = none def p_number(p): """number : integer | float""" p[0] = p[1] def p_sequence(p): """sequence : list_el comma sequence | list_el""" if len(p) == 4: p[0] = p[1] + p[3] else: p[0] = p[1] def p_list_el(p): """list_el : number | list""" p[0] = p[1]
edit:
quick explanation on tokens: in script should boil down token or character you've defined (so it's legal add). specifying them tokens, it's easier read , work with.
Comments
Post a Comment