How to count all even numbers in a list

前端 未结 2 660
南旧
南旧 2021-01-23 00:50

Please help me with how to count even numbers in a list in Prolog. I am a beginner, just started learning Prolog yesterday. I know to count the elements in the list is

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-23 01:41

    If your Prolog system offers clpfd, you can use the meta-predicate tcount/3 in combination with even_truth/2. Here's how:

    ?- tcount(even_truth, [1,2,3,5,7,9,10], N_even).
    N_even = 2.
    

    Both predicates (tcount/3 and even_truth/2) are monotone and preserve logical-purity! This makes them very robust and enables you to always get logically sound answers.

    Consider the following more general query:

    ?- Xs = [_,_,_], tcount(even_truth, Xs, N_even).
    Xs = [_A,_B,_C], N_even = 0, _A mod 2 #= 1, _B mod 2 #= 1, _C mod 2 #= 1 ;
    Xs = [_A,_B,_C], N_even = 1, _A mod 2 #= 1, _B mod 2 #= 1, _C mod 2 #= 0 ;
    Xs = [_A,_B,_C], N_even = 1, _A mod 2 #= 1, _B mod 2 #= 0, _C mod 2 #= 1 ;
    Xs = [_A,_B,_C], N_even = 2, _A mod 2 #= 1, _B mod 2 #= 0, _C mod 2 #= 0 ;
    Xs = [_A,_B,_C], N_even = 1, _A mod 2 #= 0, _B mod 2 #= 1, _C mod 2 #= 1 ;
    Xs = [_A,_B,_C], N_even = 2, _A mod 2 #= 0, _B mod 2 #= 1, _C mod 2 #= 0 ;
    Xs = [_A,_B,_C], N_even = 2, _A mod 2 #= 0, _B mod 2 #= 0, _C mod 2 #= 1 ;
    Xs = [_A,_B,_C], N_even = 3, _A mod 2 #= 0, _B mod 2 #= 0, _C mod 2 #= 0.
    

提交回复
热议问题