【发布时间】:2023-03-22 08:48:01
【问题描述】:
所以我试图在 SML 中创建一个解析器程序,提示用户输入一个表达式。然后它会告诉输入的表达式是后缀、前缀还是中缀,然后显示结果。这是我想要它做的一个例子:
Enter Expression: "* + 2 3 4"
Postfix: 2 3 + 4 *
Prefix: * + 2 3 4
Infix: (2 + 3) * 4
*
\-- +
\-- 2
\-- 3
\-- 4
我在创建函数以将结果输出到屏幕时遇到问题,我不确定我是否正确地执行了该方法。在我首先弄清楚转换之前,我什至不会专注于输出树。
fun infix_postfix(PostfixString,operatorStack,expList) =
if null expList then operatorStack
else
if(hd expList = #"^" orelse
hd expList = #"*" orelse
hd expList = #"/" orelse
hd expList = #"+" orelse
hd expList = #"-" = true)
then
hd expList:: operatorStack
else
infix_postfix(hd expList :: PostfixString, operatorStack, tl expList);
val x = "+12";
val expList = (explode x);
val PostfixString = [];
val operatorStack = [#"a"];
infix_postfix(PostfixString, operatorStack, expList);
我觉得我应该在第二个 if 语句中放置一个递归方法(检查与运算符是否相等),但由于 Alice SML 语法的限制,它不允许我这样做。任何帮助将不胜感激,我是否朝着正确的方向前进?
这是控制台中的结果:
val infix_postfix : char list * char list * char list -> char list = _fn
val x : string = "+12"
val expList : char list = [#"+", #"1", #"2"]
val PostfixString : 'a list = []
val operatorStack : char list = [#"a"]
val it : char list = [#"+", #"a"]
仅供参考:我在 Alice Interpreter Environment 中执行此操作
【问题讨论】:
标签: parsing sml prefix postfix-notation infix-notation