简体   繁体   中英

Prolog List Neighbour of a Element

I am having problems with list of prolog. I want to make this:

    [1,2,3,4,5]
    [5,6,9,12,10]

You take a number for example 3, and you do a plus operation with the neighbours so the operation is 2+3+4 = 9. For the first and the last element you pretend there is an imaginary 1 there.

I have this now:

sum_list([A,X,B|T], [Xs|Ts]):-
    add(A,X,B,Xs),
    sum_list([X,B|T], Ts).

I haven't consider the first and the last element. My problem is I don't know how to get the element before and the next and then how to move on.

Note: I not allow to use meta-predicates.

Thanks.

I'm not sure how you calculated the first 5. The last 10 would be 4 + 5 + implicit 1. But following that calculation, the first element of your result should be 4 instead of 5?

Anyways, that doesn't really matter in terms of writing this code. You are actually close to your desired result. There are of course multiple ways of tackling this problem, but I think the simplest one would be to write a small 'initial' case in which you already calculate the first sum and afterwards recursively calculate all of the other sums. We can then write a case in which only 2 elements are left to calculate the last 'special' sum:

% Initial case for easily distinguishing the first sum
initial([X,Y|T],[Sum|R]) :-
    Sum is X+Y+1,
    others([X,Y|T],R).

% Match on 2 last elements left
others([X,Y],[Sum|[]]) :-
    Sum is X+Y+1.

% Recursively keep adding neighbours
others([X,Y,Z|T],[Sum|R]) :-
    Sum is X+Y+Z,
    others([Y,Z|T],R).

Execution:

?- initial([1,2],Result)
   Result = [4,4]

?- initial([1,2,3,4,5],Result)
   Result = [4, 6, 9, 12, 10]

Note that we now don't have any cases (yet) for an empty list or a list with just one element in it. This still needs to be covered if necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM