(Prolog) Parsing Lisp s-expressions Into Prolog Terms -
i have written parser in prolog takes tokenized list , should homecoming look variable unified value of evaluated equation:
tokens = ['(', is, v('x',3),'(', +, 1, 2, ')', ')' ] expr = (3 1 + 2)
at present, parser returning following:
expr [is, _g32432, '(', +, 1, 2, ')'|_g19343]
does have thought how can prepare parser? have included code below:
%definite clause grammar (dcg) lisp s-expressions expression(n) --> atom(n). expression(n) --> integer(n). expression(n) --> variable(n). expression(n) --> list(n). list(n) --> ['('], sequence(n), [')']. sequence(_) --> []. sequence([h|t]) --> expression(h), sequence(t). %atom(_) --> []. atom(n) --> [n],{atom(n)}. %variable(_) --> []. variable(n) --> [v(_,n)],{var(n)}. %integer(_) --> []. integer(n) --> [n],{integer(n)}. evaluate(string, expr):- tokenize(string, tokens), expression(expr,tokens,[]), write('expression: '), write_term(expr, [ignore_ops(true)]).
edit: below working version of parser:
expression(n) --> atom(n). %an atom type of look expression(n) --> integer(n). %an integer type of look expression(n) --> variable(n). %a variable type of look expression(m) --> list(n),{m=..n}. list(n) --> ['('], sequence(n), [')']. %a sequence within parens type of list sequence([]) --> []. %a sequence can empty sequence([h|t]) --> expression(h), sequence(t). %a sequence can composed of look % sequence([]) --> []. %and sequence atom(_) --> []. atom(n) --> [n],{atom(n),n \= '(', n \= ')'}. %parens not atoms, other prolog atoms % if n variable , within v(label,x) info structure, % var in grammar variable(n) --> [v(_,n)],{var(n)}. %variable(_) --> []. %integer(_) --> []. integer(n) --> [n],{integer(n)}.
one of input tokens [1]. notice never match rule [2] since n
integer , not variable (also, 'x'
atom , not variable).
[1] v('x',3) [2] variable(n) --> [v(_,n)],{var(n)}.
changing [2] [3] fixes problem.
[3] variable(n) --> [n], {var(n)}.
ps: create sure close resulting look in base of operations case sequence//1
replacing corresponding line [4].
[4] sequence([]) --> [].
parsing prolog lisp dcg s-expression
No comments:
Post a Comment