home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #26 / NN_1992_26.iso / spool / comp / lang / prolog / 2052 < prev    next >
Encoding:
Text File  |  1992-11-10  |  2.0 KB  |  71 lines

  1. Newsgroups: comp.lang.prolog
  2. Path: sparky!uunet!utcsri!newsflash.concordia.ca!ccu.umanitoba.ca!mizar.cc.umanitoba.ca!eeserv.ee.umanitoba.ca!zyang
  3. From: zyang@eeserv.ee.umanitoba.ca (Zhengguang Yang)
  4. Subject: Re: pointers needed on list processing
  5. Message-ID: <BxGy34.EKM@ccu.umanitoba.ca>
  6. Keywords: sub sum, nested list
  7. Sender: news@ccu.umanitoba.ca
  8. Nntp-Posting-Host: rye.ee.umanitoba.ca
  9. Organization: University of Manitoba, Winnipeg, Canada
  10. References: <BxGLnG.CD4@ccu.umanitoba.ca>
  11. Date: Mon, 9 Nov 1992 21:52:15 GMT
  12. Lines: 57
  13.  
  14. zyang@ccu.umanitoba.ca (Z. Yang) writes:
  15.  
  16. >Hi, netters,
  17.  
  18. >I am new in prolog and have some difficulty in list processing. What I want to
  19. >do is write a predicate, ie. called 'subsum', which does following,
  20.  
  21. >?- subsum([L1,L2,...],NewList).
  22. >NewList = [Sum_of_L1,Sum_of_L2,...]
  23.  
  24. >where L1, L2 etc. are lists themselves(could be nested).
  25.  
  26. >Any pointers will be appreciated.
  27. >Thanks in advance to all kind souls.
  28.  
  29. >-zgy
  30.  
  31. I kind of figured it out(see following) by calling some pre-defined
  32. predicates. Still not satisfied, though. Can it be done in a simplier way??
  33. Or, is there a written predicate out there doing the same thing?
  34.  
  35. Any better ideas appreciated.
  36. Thanks.
  37.  
  38. -zgy
  39.  
  40. --- predicate 'subsum' begins -----
  41. % consider a list of lists LL = [L1,L2,...]. obtain the list of 
  42. % individual listsums, ie. LLS = [L1sum,L2sum,...]
  43.  
  44. subsum([],[]).                % boundary condition
  45. subsum([L1|Rest],LLS):-
  46.     flatten(L1,FlatL1),        % flatten L1
  47.     listsum(FlatL1,L1sum),        % sum of L1: L1sum
  48.     subsum(Rest,LLS1),        % sums of L2, L3, ...
  49.     add(L1sum,LLS1,LLS).        % add L1sum in front of [L2sum,...]
  50.  
  51. flatten([Head|Tail],FlatList):-        % flatten a list
  52.         flatten(Head,FlatHead),
  53.         flatten(Tail,FlatTail),
  54.         concat(FlatHead,FlatTail,FlatList),
  55.         !.
  56. flatten([],[]).
  57. flatten(X,[X]).
  58.  
  59. concat([],L,L).                % concatenate two lists into one
  60. concat([X|L1],L2,[X|L3]):-
  61.         concat(L1,L2,L3).
  62.  
  63. listsum([],0).                % sum of all entries in a list
  64. listsum([H|T],Sum):-
  65.         listsum(T,Sum1),
  66.         Sum is H + Sum1.
  67.  
  68. add(X,L,[X|L]).                % add an element in front of list L
  69.  
  70.  
  71.