使用未知变量的Prolog求解前缀算术表达式 [英] Prolog solving prefix arithmetic expression with unknown variable

查看:123
本文介绍了使用未知变量的Prolog求解前缀算术表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Prolog中创建一个算术求解器,可以对数字> = 2进行+,-,*,^操作.也应该可以在其中有一个变量x.输入应为列表中的前缀表达式.

I want to make an arithmetic solver in Prolog that can have +,-,*,^ operations on numbers >= 2. It should also be possible to have a variable x in there. The input should be a prefix expression in a list.

我制作了一个程序,将前缀格式的算术表达式解析为语法树.这样:

I have made a program that parses an arithmetic expression in prefix format into a syntax tree. So that:

?- parse([+,+,2,9,*,3,x],Tree).
Tree = plus(plus(num(2), num(9)), mul(num(3), var(x))) .

(1)在此阶段,我想扩展该程序,以便能够针对给定的x值求解它.这应该通过添加另一个谓词 evaluate(树,值,解决方案)来完成,该谓词给定未知x的值,然后计算解决方案.

(1) At this stage, I want to extend this program to be able to solve it for a given x value. This should be done by adding another predicate evaluate(Tree, Value, Solution) which given a value for the unknown x, calculates the solution.

示例:

?- parse([*, 2, ^, x, 3],Tree), evaluate(Ast, 2, Solution).
Tree = mul(num(2), pow(var(x), num(3))) ,
Solution = 16.

由于缺乏Prolog技能,我不确定如何解决此问题,但是我需要一种将var(x)设置为num(2)的方法,如本例所示(因为x = 2).也许可以使用Prolog中的成员来做到这一点.然后我必须使用 is/2

I'm not sure how to solve this problem due to my lack of Prolog skills, but I need a way of setting the var(x) to num(2) like in this example (because x = 2). Maybe member in Prolog can be used to do this. Then I have to solve it using perhaps is/2

编辑:我试图解决它.出现错误:"未定义过程:评估/3但是,有以下定义:评估/5 "

Edit: My attempt to solving it. Getting error: 'Undefined procedure: evaluate/3 However, there are definitions for: evaluate/5'

evaluate(plus(A,B),Value,Sol) --> evaluate(A,AV,Sol), evaluate(B,BV,Sol), Value is AV+BV.
evaluate(mul(A,B),Value,Sol) --> evaluate(A,AV,Sol), evaluate(B,BV,Sol), Value is AV*BV.
evaluate(pow(A,B),Value,Sol) --> evaluate(A,AV,Sol), evaluate(B,BV,Sol), Value is AV^BV.
evaluate(num(Num),Value,Sol) --> number(Num).
evaluate(var(x),Value,Sol) --> number(Value).

(2)我也希望能够以后缀形式表示它.具有谓词 postfixform(树,后缀列表)

(2) I'd also want to be able to express it in postfix form. Having a predicate postfixform(Tree, Postfixlist)

示例:

?- parse([+, *, 2, x, ^, x, 5 ],Tree), postfix(Tree,Postfix).
Tree = plus(mul(num(2), var(x)), pow(var(x), num(5))) ,
Postfix = [2, x, *, x, 5, ^, +].

任何对(1)(2)的帮助将不胜感激!

Any help with (1) and (2) would be highly appreciated!

推荐答案

您无需像现在那样使用语法.您应该使用正常规则.

You don't need to use a grammar for this, as you are doing. You should use normal rules.

这是您需要遵循的模式.

This is the pattern you need to follow.

evaluate(plus(A,B),Value,Sol) :- 
   evaluate(A, Value, A2),
   evaluate(B, Value, B2),
   Sol is A2+B2.

还有

evaluate(num(X),_Value,Sol) :- Sol = X.
evaluate(var(x),Value,Sol) :- Sol = Value.

这篇关于使用未知变量的Prolog求解前缀算术表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆