0
votes

I am working on a prolog program, but I have no idea to finish the program. Here is the requirement.

The program allows multiple fact, however, the length of list in each fact must equals

Example 1

%fact
f(first, [1, 6, 10]).
f(second, [7, 3, 8]).
f(third, [5, 9, 5]).

Example 2

%fact
f(first, [1,6,10]).
f(second, [7,3,8]).
f(third, [5,9,5]).
f(fourth, [7,3,9]).
f(fifth, [7,7,2]).

Example 3

%fact
f(first, [1,6,10,54,11,6]).
f(second, [7,3,8,34,2,7]).

Now, I need to write a predicate sum_list(), so that users can do the following things.

Example 1

?-sum_list([first,second,third], Even, Result).
Even = 1
Result = [13,18,23]

Example 2

?-sum_list([first,second,third,fourth,fifth], Even, Result).
Even = 2
Result = [27,28,34]

Example 3

?-sum_list([first,second], Even, Result).
Even = 3
Result = [8,9,18,88,13,13]

Result is a list which contains the sum of each element in the corresponding fact lists.

Even is counting the number of even number in the Result, in Example 2, only 28 and 34 are even, so Even = 2.

Thanks.

Thanks for SimoV8's hints, and I get some ideas to solve in the way:

%fact
f(first, [1, 6, 10]).
f(second, [7, 3, 8]).

sum_list([Head|Tail], E, R) :- 
    f(Head, P),
    sw(P, Tail, [R]),
    even(E,R).

sw(H1, [Head|Tail], [X|R]) :-
    f(Head,S),
    sum(H1, S, X),
    sw(X, Tail, R).

sw(_, [], []).

sum([H1|T1],[H2|T2],[X|L3]) :- 
    sum(T1,T2,L3), X is H1+H2.

sum([],[],[]).

even(E, [X|R]) :-
    even(E2, R),
    ((X mod 2) =:= 1 -> E is E2; E is E2 + 1).

even(0, []).

However, the answer only accepts two f(), if more than two f(), it will return FALSE

1
Have you attempted anything? Can you show what you have done so far?lurker
Actually I am a prolog beginner, there are many prolog things that I don't know. I have an idea to implement this program on java, but I know that there is a big difference between java and prolog(for example I can't use return value in prolog), and that makes me don't know how to start.N.Ronbin

1 Answers

0
votes

Try this:

sum_list([], 0, []).
sum_list([H|T], E, [RH|RT]):- f(H, X), 
                              sum(X, RH), 
                              sum_list(T, E2, RT), 
                              ((RH mod 2) =:= 1 -> E is E2; E is E2 + 1).
 sum([], 0).
 sum([H|T], S1):- sum(T, S2), S1 is H + S2.