Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog count list elements higher than n

Tags:

prolog

I'm kinda new to Prolog so I have a few problems with a certain task. The task is to write a tail recursive predicate count_elems(List,N,Count) condition List_Element > N, Count1 is Count+1.

My approach:

count_elems( L, N, Count ) :-
   count_elems(L,N,0).
count_elems( [H|T], N, Count ) :-
   H > N ,
   Count1 is Count+1 ,
   count_elems(T,N,Count1).
count_elems( [H|T], N, Count ) :-
   count_elems(T,N,Count).

Error-Msg:

ERROR: toplevel: Undefined procedure: count_elems/3 (DWIM could not correct goal)

I'm not quite sure where the problem is. thx for any help :)

like image 782
vicR Avatar asked Jul 20 '26 04:07

vicR


1 Answers

If you want to make a tail-recursive version of your code, you need (as CapelliC points out) an extra parameter to act as an accumulator. You can see the issue in your first clause:

count_elems(L, N, Count) :- count_elems(L,N,0).

Here, Count is a singleton variable, not instantiated anywhere. Your recursive call to count_elems starts count at 0, but there's no longer a variable to be instantiated with the total. So, you need:

count_elems(L, N, Count) :-
    count_elems(L, N, 0, Count).

Then declare the count_elem/4 clauses:

count_elems([H|T], N, Acc, Count) :-
    H > N,                            % count this element if it's > 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's <= 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 an "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 pointed out, your stated error message is probably due to not reading in your prolog source file.

like image 145
lurker Avatar answered Jul 23 '26 15:07

lurker