Resolved: Prolog prefix sum of a list

In this post, we will see how to resolve Prolog prefix sum of a list

Question:

I want to implement the prolog predicate prefixSum(L, R) that calculates the prefix sum of a list i.e:
Here is my solution so far:
What can I try next?

Best Answer:

Your original code,
Has these problems:
  • The code is syntactically incorrect, as the 2nd clause is not terminated by ..
  • In the 3rd clause, the variable R will always be unbound unless you’ve provided a bound list as the 2nd argument to prefixSum/3, meaning Rs is X+R will fail.

The key to what you are trying to accomplish is that as you traverse the list, you need to track the sum previously computed as you go.
That leads to an implementation like this:

If you have better answer, please add a comment about this, thank you!

Source: Stackoverflow.com