1

Please help me! I need to find sum of the elements of two lists of different length. It should look like:

?-p([1,2,3],[1,2,3,9],L),write(L),nl.
L = [2,4,6,9].

p([],_,[]).
p(_,[],[]).
p([H1|T1],[H2|T2],[H|T]):-H is H1 + H2,p(T1,T2,T).
?-p([1,2,3],[1,2,3],L),write(L),nl.

So I've got some troubles with different length of lists. I don't know how to do it. Thanks for your help! Tanya.

4

2 に答える 2

3

可能であれば、より短く決定論的なコードを好みます。

p([X|Xs], [Y|Ys], [Z|Zs]) :-
    Z is X + Y,
    !, p(Xs, Ys, Zs).
p([], Ys, Ys) :- !.
p(Xs, [], Xs).
于 2013-05-26T20:01:21.663 に答える