对于由整数和数字列表组成的异构列表,请编写谓词以计算 表示为子列表的所有数字的总和。 例如:[1,[2、3],4、5,[6、7、9],10、11,[1、2、0],6] => [8、2、2]。>
% The predicate reverses the given list.
% reverseList(L - list of integers, X - output, Z - auxiliary list )
% reverseList(i,o,i)
reverseList([],Z,Z).
reverseList([H|T],X,Rest):- reverseList(T,X,[H|Rest]).
% The predicate returns the reverse list of the given list.
% wrapperReverseList(L - list of integers, R - output list).
% wrapperReverseList(i,o)
wrapperReverseList(L,R):- reverseList(L,R,[]).
% The predicate adds two numbers represented as lists.
% sum(L1 - first number as list, L2 - second number as list,
% T - transport integer, R - result list)
% sum(i,i,i,o).
sum([],[],T,[T]):-T=\=0,!.
sum([],[],_,[]):-!.
sum([],[L],T,[L]):-T=0,!.
sum([L],[],T,[L]):-T=0,!.
sum([H1|T1],[H2|T2],T,[Hs|Ts]):-
S is H1+H2+T,
Tn is S div 10,
Hs is S mod 10,
sum(T1,T2,Tn,Ts).
% The predicate adds two number represented as lists.
% wrapperSum(L1 - first number as list, L2 - second number as list, R -
% result list )
% wrapperSum(i,i,o)
wrapperSum(L1,L2,Ls):-
wrapperReverseList(L1,L1i),
wrapperReverseList(L2,L2i),
sum(L1i,L2i,0,LAux),
wrapperReverseList(LAux,Ls).
% until here the code checks out, adding two lists works
% now i want to go through a list, check for each element if it is a list,
% and if it is, add it to the result
addLists([],[],_).
addLists([H|T],Laux,R):-is_list(H),
wrapperSum(H,Laux,R1),
R is R1,
addLists(T,Laux,R).
addLists([H|T],Laux,R):-number(H),
addLists(T,Laux,R).
答案 0 :(得分:0)
这应该有效:
add_all(L, LR):-
foldl(add_all1, L, 0, R),
number_codes(R, C),
maplist([X,Y]>>(Y is X-0'0), C, LR).
add_all1(Item, R, R1):-
(number(Item)-> R=R1 ;
(
atomic_list_concat(Item, N1),
atom_number(N1, N),
R1 is R+N
)
).
样品运行:
?- add_all( [1, [2, 3], 4, 5, [6, 7, 9], 10, 11, [1, 2, 0], 6], Result).
Result = [8, 2, 2].