开发者

Prolog Common Differences, Next Number in Polynomial Sequence

I'm trying to implement a simple algorithm for common differences(http://www.purplemath.com/modules/nextnumb.htm) in Prolog (to which I am pretty new) and I seem to be having trouble coming up with the right rules. I have:

nextitem([A|B], NextI):-lastitem([A|B],X), 
rowbelow([A|B],[Z]),lastitem([Z],Y), nextI is X+Y.
nextitem([],0).

%% recursive case: ignore first item, seek last item of rest of list
lastitem([First | Rest], Last) :-lastitem(Rest, Last).
lastitem([OnlyOne], OnlyOne).

%%at least two things in the list
rowbelow([A,B|T], [X|Y]) :-X is B-A, rowbelow([B|T],Y). 
rowbelow([A,开发者_如何学CB|T], [X]) :-X is B-A.

The problem seems to be in my next item, (and it feels like I should have a recursive call in next item somewhere, but maybe not?)

for example: rowbelow([6,7,14,33],X). produces the proper [1,7,19] (for the poly x^3+6)

but next item does not produce 70..

The trace seems like my row below call in next item is wrong, and I think I'm missing a recursive call to keep moving to the row...

Any ideas how to fix the nextitem rules?? Really appreciate any help as I'm probably 20 hrs in on this and it hasn't 'just clicked' yet...


You have a typo in your nextitem rule, NextI should be case-sensitive and you have it as nextI in the definition. Also, do you need the list brackets around [Z], rowbelow results in a list for that operand, so they are not needed. So you end up with:

nextitem([A|B], NextI):-lastitem([A|B],X),
rowbelow([A|B],Z),lastitem(Z,Y), NextI is X+Y.
nextitem([],0).

With that in place, nextitem([6,7,14,33],X) results in X = 52, which is what would be given from the logic you have in place.

To trace through:

  • lastitem([6,7,14,33],X) would make X = 33
  • rowbelow([6,7,14,33], Z) would give Z = [1,7,19] as you state
  • lastitem([1,7,19],Y) makes Y = 19
  • NextI is 33+19 gives NextI = 52

You are only evaluating the first level of differences, in order to get the next entry in the sequence for x^3 + 6, which is 70 as you say, you would need to add 37 to the previous value (33), which is the previous difference, 19, plus 18, which is given by the nextitem of the level below, which would be [6,12].

The target is the recursive definition, as the example website shows you, it is necessary to get down to the level where the difference is constant.

Prolog Common Differences, Next Number in Polynomial Sequence

In your case, getting down to a consistent 6.

Redefining your nextitem rule to process the lists returned by rowbelow will yield what you desire, also an additional rule is required for the singleton list, as you are not covering that eventuality.

nextitem([A|B], NextI):-lastitem([A|B],X), rowbelow([A|B],Z), nextitem(Z,Y), NextI is X+Y.
nextitem([A],A).
nextitem([],0).
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜