使用 Prolog 将后缀转换为前缀 [英] Postfix to Prefix Conversion using Prolog
问题描述
谁能帮我在PROLOG中使用堆栈概念编写一个程序,将算术表达式从后缀(反向波兰符号)转换为前缀形式.算术表达式可能包含 4 个算术运算符 +、-、/、* 和一元函数:sin、cos、tan、exp、log 和 sqrt.
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.
推荐答案
append/2 这是一个有用的列表组合器.它以相当一般的方式允许在任意数量的列表之间建立关系.我将在这里只展示基本的,你需要完成你的作业,添加一些细节作为一元函数,定义 isop/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]).
一个小测试:
?- pos2pre([1,5,*,2,+],X).
X = [+, *, 1, 5, 2].
我认为您应该尝试编写相同的逻辑,但使用 append/3,这将有助于您了解程序的工作原理.
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 将后缀转换为前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!