Most probably I couldn't properly phrase my search keywords. What I'm trying to do is to recursively evaluate difference of consecutive entries in a list and keep adding them to a global counter. The challenge is the circular clause in the end so that if the list is [5,4,3,2,1]
, the predicate should return (5-4)+(4-3)+(3-2)+(2-1)+(1-5)=0
.
What I have so far is as follows:
circularSumOfDifferences([_],0).
circularSumOfDifferences([E1,E2|List],Sum) :-
Diff is E1-E2,
circularSumOfDifferences([E2|List],SoD),
Sum is Diff+SoD.
Now I have thought of defining another predicate to add the first element of the list at the tail of given list and calling the new list in conjunction with the query: copyHeadToTail([5,4,3,2,1],Result),circularSumOfDifferences(Result,C).
It won't be difficult to realise but it doesn't look very elegant to me. I wonder if there's a way to define just one predicate circularSumOfDifferences(+L,-SoD)
that recurses through the list and runs one statement in the end (or beginning) for that one substraction,i.e. 1-5
.