计算列表中的数字

时间:2017-01-16 18:37:29

标签: list prolog

我在计算列表中给定数字的出现时遇到问题。例如,如果我们有一个类似L = [4,5,6,4,3,4,2,4,5,6,7,4]的列表,并且我想计算列表中有多少4,则答案为5

我尝试在prolog中实现此功能,但gprolog仅向我显示no作为答案:

count_occ([], 0).
count_occ([H|T], L) :- count_occ(T, N), H =:= 4, L is N + 1.

我不知道为什么。

2 个答案:

答案 0 :(得分:3)

我抓住了这个。我把它做得非常详细,所以很容易理解:

% count_occurences(+List, +DesiredElement, -NumOccurences)

count_occurences([], _, 0).

count_occurences([H|T], DesiredElement, NumOccurences) :-
    H =\= DesiredElement,
    count_occurences(T, DesiredElement, NumOccurences).

count_occurences([H|T], DesiredElement, NumOccurences) :-
    H =:= DesiredElement,
    count_occurences(T, DesiredElement, N),
    NumOccurences is N + 1.

使用条件表达式,最后2个谓词可以合并为一个:

% count_occurences(+List, +DesiredElement, -NumOccurences)

count_occurences([], _, 0).

count_occurences([H|T], DesiredElement, NumOccurences) :-
    count_occurences(T, DesiredElement, N),
    (H =:= DesiredElement ->       /* if H is DesiredElement */
        NumOccurences is  N + 1;   /* "then" */
        NumOccurences is  N        /* "else" */
    ).

答案 1 :(得分:2)

我认为问题在于,当H不是4时,您不提供Prolog可以采用的条款。然而,这个很简单:你只需执行递归调用:

count_occ([H|T],N) :-
    H \= 4,
    count_occ(T,N).

或完整实施:

count_occ([],0).
count_occ([4|T],N1) :-
    count_occ(T,N),
    N1 is N+1.
count_occ([H|T],N) :-
    H \= 4,
    count_occ(T,N).