Sum of even, product of odd numbers in Prolog

后端 未结 4 2053
悲&欢浪女
悲&欢浪女 2020-12-21 09:33

I have a list of numbers, I need to calculate the sum of the even numbers of the list and the product of the odd numbers of the same list. I\'m new in Prolog, and my searche

4条回答
  •  [愿得一人]
    2020-12-21 10:12

    Use clpfd!

    :- use_module(library(clpfd)).
    

    Building on meta-predicate foldl/4, we only need to define what a single folding step is:

    sumprod_(Z,S0,S) :-
       M #= Z mod 2,
       rem_sumprod_(M,Z,S0,S).
    
    rem_sumprod_(0,Z,S0-P,S-P) :- 
       S0 + Z #= S.
    rem_sumprod_(1,Z,S-P0,S-P) :- 
       P0 * Z #= P.
    

    Let's fold sumprod_/3 over the list!

    l_odd_even(Zs,ProductOfOdds,SumOfEvens) :-
       foldl(sumprod_,Zs,0-1,SumOfEvens-ProductOfOdds).
    

    Sample query:

    ?- l_odd_even([1,2,3,4,5,6,7],Odd,Even).
    Odd = 105,
    Even = 12.
    

    Alternatively, we can define sumprod_/3 even more concisely by using if_/3 and zeven_t/3:

    sumprod_(Z,S0-P0,S-P) :-
       if_(zeven_t(Z), (S0+Z #= S, P0=P),
                       (P0*Z #= P, S0=S)).
    

提交回复
热议问题