expression - Prolog - How can obtain the prefix form of a math calculation given its usual form? -
i'm new in prolog , program calculator. need program predicate process given arithmetic expression, written in usual form (infix form), such obtain prefix form. elements of expression grouped sublists 3 elements, of following form [operator, term1, term2], such terms can in turn lists. predicate called parse should defined , work in example:
?-parse([1,+,2,*,3],pf). pf=[+,1,[*,2,3]]
you may use atom_to_term/3
, =../2
obtain prefix form of arithmetic expression. atomic_list_concat/2
create atom input list, atom_to_term
build term (which infix representation of arithmetic expression). then, using univ (=..
), can recursively obtain prefix notation.
i.e.:
parse(lexp, pf):- atomic_list_concat(lexp, exp), atom_to_term(exp, term, _), parse1(term, pf). parse1(term, pf):- term =.. [pf]. parse1(term, [op, left, right]):- term =.. [op, tleft, tright], parse1(tleft, left), parse1(tright, right).
test case:
?- parse([1,+,2,*,3],pf). pf = [+, 1, [*, 2, 3]]
Comments
Post a Comment