Convert A String to List in Prolog -
i prolog newbie , stuck @ parsing string list. have string of form. want read polynomial string , convert string. want convert input string
2x^3 + x^2 - 4x^1 - 8
to
[[2,3], [1,2], [-4, 1], [-8, 0]]
how can achieve functionality?
this problem solved in 2 steps:
- lexical analysis / tokenizer: convert string list of tokens represent each of possible elements of expression: numbers, variable names , operators. representations maybe, instance, terms
number(v)
,vname(n)
,op(op)
; may wish use different terms additive operators separate monomials , exponent operator. - syntactic analysis / parser: apply grammar rules list of tokens identify monomials , convert them required representation. in case each rule have form of clause inspects appears @ beginning of tokens list find monomial , convert it.
monom([number(n),vname(x),op(exp),number(e)|ts],[[n,e]|ms]) :- !, monom(ts,ms). monom([number(n),vname(x),op(+)|ts],[[n,1]|ms]) :- !, monom([op(+)|ts],ms).
note these rules not check whether variables have same name. issue using minus sign of monomial. hope able cope this.
Comments
Post a Comment