I'm new in prolog and I would like to program a calculator. For that I need to program a predicate that process the given arithmetic expression, written in the usual form (infix form), such that to obtain its prefix form. The elements of the expression will be grouped into sublists with 3 elements, of the following form [operator, term1, term2], such that the terms can be in their turn lists. A predicate called parse should be defined and work like in this example:
?-parse([1,+,2,*,3],PF).
PF=[+,1,[*,2,3]]
You may use atom_to_term/3
and =../2
to obtain a prefix form of an arithmetic expression. atomic_list_concat/2
will create an atom from your input list, then atom_to_term
will build a term (which will be the infix representation of your arithmetic expression). Then, using univ (=..
), you can recursively obtain the 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]]