If you want to make a tail recursive version of your code, you need (as CapelliC points out) an additional parameter to work as a battery. You can see the problem in your first sentence:
count_elems(L, N, Count) :- count_elems(L,N,0).
Here Count is a singleton variable not created anywhere. Your recursive call to count_elems starts at 0 , but there is no longer a variable to be created along with the result. So you need to:
count_elems(L, N, Count) :- count_elems(L, N, 0, Count).
Then declare the count_elem/4 sentences:
count_elems([H|T], N, Acc, Count) :- H > N, % count this element if it > N Acc1 is Acc + 1, % increment the accumulator count_elems(T, N, Acc1, Count). % check the rest of the list count_elems([H|T], N, Acc, Count) :- H =< N, % don't count this element if it <= N count_elems(T, N, Acc, Count). % check rest of list (w/out incrementing acc) count_elems([], _, Count, Count). % At the end, instantiate total with accumulator
You can also use the if-else structure for count_elems/4 :
count_elems([H|T], N, Acc, Count) :- (H > N -> Acc1 is Acc + 1 ; Acc1 = Acc ), count_elems(T, N, Acc1, Count). count_elems([], _, Count, Count).
Also, as CapelliC noted, your reported error message is probably due to the fact that you are not reading the prolog in the source file.