使用Prolog中的累加器评估多项式的​​评估问题 [英] Evaluation issue using accumulators in Prolog to evaluate a polynomial

查看:97
本文介绍了使用Prolog中的累加器评估多项式的​​评估问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要写一个谓词eval(P,A,R),其中:

P代表多项式系数列表,即1 + 2x + 3x ^ 2表示为[1,2,3]。
A表示X的值。

R是X处的多项式的结果= A。

I need to write a predicate eval(P,A,R), where:
P represents a list of polynomial coefficients, i.e. 1+2x+3x^2 is represented as [1,2,3].
A represents the value for X.
R is the result of the polynomial at X=A.

示例: eval([3,1,2],3,R)产生R =24。 *编辑,之前错误的示例

Example: eval([3,1,2],3,R) produces R = 24. *edit, previously incorrect example

我正尝试在立即学习Prolog

我的算法:

0。将结果和指数变量初始化为0。

1 。

2.将列表的头乘以A ^(指数)。

3.更新结果和指数。

My Algorithm:
0. Initialize result and exponent variables to 0.
1. Take the head of the list.
2. Multiply the head of the list by A^(exponent).
3. Update result and exponent.

我的代码:

eval(P,A,R) :- accEval(P,A,0,0,R).      
accEval(([H|T]),A,Pow,Accres,R) :- 
        Rnew is (Accres+H*(A**Pow)), 
        Pownew is Pow+1, 
        R = Accres, 
        accEval(T,A,Pownew,Rnew,Rnew).  % *See below
accEval([],A,Pow,Accres,Accres).

% *Previously, when the second Rnew in this line was R instead, output was "no".

产生跟踪:

| ?- eval([1,2],3,R).
  1    1  Call: eval([1,2],3,_20) ? 
  2    2  Call: accEval([1,2],3,0,0,_20) ? 
  3    3  Call: _126 is 0+1*3**0 ? 
  3    3  Exit: 1.0 is 0+1*3**0 ? 
  4    3  Call: _157 is 0+1 ? 
  4    3  Exit: 1 is 0+1 ? 
  5    3  Call: accEval([2],3,1,1.0,1.0) ? 
  6    4  Call: _218 is 1.0+2*3**1 ? 
  6    4  Exit: 7.0 is 1.0+2*3**1 ? 
  7    4  Call: _249 is 1+1 ? 
  7    4  Exit: 2 is 1+1 ? 
  8    4  Call: accEval([],3,2,7.0,7.0) ? 
  8    4  Exit: accEval([],3,2,7.0,7.0) ?  % We have the correct answer.
  5    3  Exit: accEval([2],3,1,1.0,1.0) ? % Wait! What are you doing!?
  2    2  Exit: accEval([1,2],3,0,0,0) ?   % Why is this falling back out?
  1    1  Exit: eval([1,2],3,0) ? 

R = 0  % Incorrect. The answer should be 7.

如我的代码所述,先前的尝试没有为R产生任何价值,

As noted in my code, previous attempts have produced no value for R, instead producing "no" or in other implementations "yes".

为什么结果丢失并且

推荐答案

应该在变量末尾与累加器值统一的变量?递归已绑定到值。使用累加器的方式如下:

The variable that is supposed to be unified with the accumulator value at the end of the recursion is already bound to a value. The way that you use accumulators is as follows:


  • 当您首次调用谓词时,给累加器一个初始值

  • 使用累加器将累加值传递给递归调用

  • 在递归结束子句中将结果与累加器统一

根据经验,谓词开头的Result变量与传递给递归调用的变量相同。这样,一旦它与末尾的实际结果统一(在end-of-递归子句中),它也将从递归中传递给调用者。

As a rule of thumb, the Result variable in the head of the predicate is the same variable that is passed down to the recursive call. This way, once it gets unified with the actual result at the end (in the end-of-recursion clause), it will also be passed up out of the recursion to the caller.

这篇关于使用Prolog中的累加器评估多项式的​​评估问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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