I am trying to understand recursion in Prolog, but it is certainly different than how it is in other languages like PHP, Java and C. I have been reading all the tutorials about it, but I still don't get specific, rather complicated cases.
For instance, in order to get the number of occurrences of an element in a list we have:
occurrence([], _, 0).
occurrence([H | T], H, N) :- !, occurrence(T, H, N1), N is N1 + 1.
occurrence([_ | T], H, N) :- occurrence(T, H, N).
which can be called using:
occurrence([1,4,9,1,2],1,R).
and it should result:
?- R=2
Why is line 3 even happening? What is it doing? I wrote this program without looking at the answer and I was done after the 2nd line. Of course it wasn't working though.
On the other hand, why is the "cut" occurring in there? I have been trying to print out the result after every call and I just get more and more confused.