Search code examples
recursionprolog

Recursive Summation with Conditional in Prolog


I was ask to do a program in Prolog which has to be able to do a summation of pair and odd numbers with a recursive structure. The rule has the following form:

sum(N,PairSum,OddSum)

With N as the number given as parameter. For Example: if N=5 then PairSum=4+2 and OddSum=5+3+1

My Code is the following

suma(0,0,0).
suma(N,SumPares,SumImpares) :-
   N>0,
   N1 is N -1,
   suma(N1,SumaP,SumaI),
   (  (0 is mod(N,2))
   -> SumPares is SumaP + (N-2)
   ;  SumImpares is SumaI +(N-2)
   ).

The code compiles successfully, it fails when i run it. For example with N=5

suma(5,SumaPares,SumaImpares)

I get the following

ERROR: Arguments are not sufficiently instantiated ERROR: In: ERROR:
[12] _9750 is _9756+(2-2)


Solution

  • After following the advices from @gusbro and inluding some others i could make to this code to work properly. The key was in the base case that was suma(2,2,1) and not suma(0,0,0). Other problem i had was my summations in the if clause were I a do N-2 and I just have to leave the N alone and not substract anything. Here is the working code:

     suma(2,2,1).
     suma(N,SumaPares,SumaImpares) :-
           N>0,
           N1 is N -1,
           suma(N1,SumaP,SumaI),
           ( 0 is mod(N,2) ->
                (SumaPares is SumaP + N, SumaImpares is SumaI)
             ;  (SumaImpares is SumaI +N, SumaPares is SumaP)
           ).
    

    Thanks a lot for the help.