2

I have just started with Prolog and now I have my first problem, which I just can't solve:

I want to give the program 3 lists and as result I want to know if their sum is equal.

So something like this:

?- sum_equal([1,2,3],[4,1,1],[5,1,0]).
true

Until now I've got this:

partsum([],0).
partsum([Head|Tail],Solution) :- 
    partsum(Tail, Solution2), 
    Solution is Head+Solution2.

sum_equal([Head|Tail],[Head2|Tail2],[Head3|Tail3]):-
    sum1=partsum([Head|Tail],sum1),
    sum2=partsum([Head2|Tail2],sum2),
    sum3=partsum([Head3|Tail3],sum3),
    sum1=:=sum2,
    sum1=:=sum3.

But now I get the following message:

evaluable 'sum1' does not exist.

Thanks for your help.

repeat
  • 18,496
  • 4
  • 54
  • 166

2 Answers2

2

In this answer, we assume that all numbers used are integers, which allows us to use :

:- use_module(library(clpfd).

To define sum_equal/3 we proceed step by step—it's as easy as one, two, three!

  1. Based on ...

    ... we define the following two auxiliary predicates:

    sum_of_zs(S,Zs) :-
       length(Zs,_),                % ensure sufficient instantiation for sum/3
       sum(Zs,#=,S).
    
    all_zs_have_the_same_sum(Zss,S) :-
       maplist(sum_of_zs(S),Zss).
    
  2. sum_equal/3 is a mere specialization of all_zs_have_the_same_sum/2:

    sum_equal(Xs,Ys,Zs) :-
       all_zs_have_the_same_sum([Xs,Ys,Zs],_).
    
  3. We're done with coding. Let's put it to good use and run the sample query given by the OP:

    ?- sum_equal([1,2,3],[4,1,1],[5,1,0]).
    true.
    
Community
  • 1
  • 1
repeat
  • 18,496
  • 4
  • 54
  • 166
1

Just a couple of things I've noticed.

Prolog variables must start with a capital letter, so sum1 needs to be Sum1 etc.

In the lines like

sum1=partsum([Head|Tail],sum1),

the sum1= should not be there because partsum is returns with a value in sum1. so the lines should be similar to

partsum([Head|Tail],Sum1),
Craunch
  • 20
  • 2
  • Thank you. Now it works. I thought you use only capital letters if you pass variables and here I give the name. But I think now I got it. – user3475727 Mar 29 '14 at 13:56