home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.prolog
- Path: sparky!uunet!utcsri!newsflash.concordia.ca!ccu.umanitoba.ca!mizar.cc.umanitoba.ca!eeserv.ee.umanitoba.ca!zyang
- From: zyang@eeserv.ee.umanitoba.ca (Zhengguang Yang)
- Subject: Re: pointers needed on list processing
- Message-ID: <BxGy34.EKM@ccu.umanitoba.ca>
- Keywords: sub sum, nested list
- Sender: news@ccu.umanitoba.ca
- Nntp-Posting-Host: rye.ee.umanitoba.ca
- Organization: University of Manitoba, Winnipeg, Canada
- References: <BxGLnG.CD4@ccu.umanitoba.ca>
- Date: Mon, 9 Nov 1992 21:52:15 GMT
- Lines: 57
-
- 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
-
-
-