I was reading a recursive function in prolog that returns the Sum of all the elements in a list as below :
sum([ ], 0).
sum( [Elem | Tail], S):- sum(Tail, S1),
S is S1 + Elem.
I can't understand two issues:
1: In the left side of ":-" we have the Goal. It means all the calculations will be done in the right side of ":-" and then we can use the Goal as a normal function. It means we give our arguments and variables that the result will be putted on them, and the right side is responsible for calculating.
But in this code the Goal, itself is calculating the Head and Tail. I mean in my mind the code should have been like this (however it doesn't work!) :
sum(Tail, S1):-sum( [Elem | Tail], S),........
Because the goal is supposed to give the arguments and the right side is in charge of calculating.
2: I cannot understand how this code works step by step. can anyone give me a very simple example like how it calculates the sum of [1,2,3]?