Postfix to Prefix Conversion using Prolog

2020-04-21 03:53发布

问题:

Can anyone help me to write a program using stack concept in PROLOG to convert an arithmetic expression from postfix(reverse polish notation) to prefix form. The arithmetic expression may contain the 4 arithmetic operators + , - , / , * and the unary functions : sin, cos, tan, exp, log and sqrt.

回答1:

append/2 it's a useful list combinator. It allows in fairly general way a relation of concatenation among an arbitrary number of lists. I'll show just the basic here, you'll need to complete your assignment adding some detail as unary functions, define isop/1

pos2pre(Pos, Pre) :-
    append([A, B, [O]], Pos), isop(O), A \= [], B \= [],
    pos2pre(A, APre),
    pos2pre(B, BPre),
    !, append([[O], APre, BPre], Pre).
pos2pre([P], [P]).

a little test:

?- pos2pre([1,5,*,2,+],X).
X = [+, *, 1, 5, 2].

I think you should try to write the same logic but using append/3, that would help you to understand how the procedure works.



标签: prolog