Thread View: comp.lang.prolog
2 messages
2 total messages
Started by Z. Yang
Mon, 09 Nov 1992 17:23
pointers needed on list processing
Author: Z. Yang
Date: Mon, 09 Nov 1992 17:23
Date: Mon, 09 Nov 1992 17:23
14 lines
845 bytes
845 bytes
Hi, netters, I am new in prolog and have some difficulty in list processing. What I want to do is write a predicate, ie. called 'subsum', which does following, ?- subsum([L1,L2,...],NewList). NewList = [Sum_of_L1,Sum_of_L2,...] where L1, L2 etc. are lists themselves(could be nested). Any pointers will be appreciated. Thanks in advance to all kind souls. -zgy
Re: pointers needed on list processing
Author: Zhengguang Yang
Date: Mon, 09 Nov 1992 21:52
Date: Mon, 09 Nov 1992 21:52
55 lines
2155 bytes
2155 bytes
zyang@ccu.umanitoba.ca (Z. Yang) writes:
>Hi, netters,
>I am new in prolog and have some difficulty in list processing. What I want to
>do is write a predicate, ie. called 'subsum', which does following,
>?- subsum([L1,L2,...],NewList).
>NewList = [Sum_of_L1,Sum_of_L2,...]
>where L1, L2 etc. are lists themselves(could be nested).
>Any pointers will be appreciated.
>Thanks in advance to all kind souls.
>-zgy
I kind of figured it out(see following) by calling some pre-defined
predicates. Still not satisfied, though. Can it be done in a simplier way??
Or, is there a written predicate out there doing the same thing?
Any better ideas appreciated.
Thanks.
-zgy
--- predicate 'subsum' begins -----
% consider a list of lists LL = [L1,L2,...]. obtain the list of
% individual listsums, ie. LLS = [L1sum,L2sum,...]
subsum([],[]). % boundary condition
subsum([L1|Rest],LLS):-
flatten(L1,FlatL1), % flatten L1
listsum(FlatL1,L1sum), % sum of L1: L1sum
subsum(Rest,LLS1), % sums of L2, L3, ...
add(L1sum,LLS1,LLS). % add L1sum in front of [L2sum,...]
flatten([Head|Tail],FlatList):- % flatten a list
flatten(Head,FlatHead),
flatten(Tail,FlatTail),
concat(FlatHead,FlatTail,FlatList),
!.
flatten([],[]).
flatten(X,[X]).
concat([],L,L). % concatenate two lists into one
concat([X|L1],L2,[X|L3]):-
concat(L1,L2,L3).
listsum([],0). % sum of all entries in a list
listsum([H|T],Sum):-
listsum(T,Sum1),
Sum is H + Sum1.
add(X,L,[X|L]). % add an element in front of list L
Thread Navigation
This is a paginated view of messages in the thread with full content displayed inline.
Messages are displayed in chronological order, with the original post highlighted in green.
Use pagination controls to navigate through all messages in large threads.
Back to All Threads