In this post, we will see how to resolve Prolog prefix sum of a list
Question:
I want to implement the prolog predicateprefixSum(L, R)
that calculates the prefix sum of a list i.e:Best Answer:
Your original code,- 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 toprefixSum/3
, meaningRs 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
Leave a Review