Postfix to Prefix Conversion using Prolog

ぐ巨炮叔叔 提交于 2020-01-11 11:26:16

问题


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.



来源:https://stackoverflow.com/questions/15022133/postfix-to-prefix-conversion-using-prolog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!