Prolog count list elements higher than n

前端 未结 3 1294
谎友^
谎友^ 2020-12-21 06:21

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

3条回答
  •  [愿得一人]
    2020-12-21 06:49

    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.

提交回复
热议问题