home *** CD-ROM | disk | FTP | other *** search
/ Liren Large Software Subsidy 9 / 09.iso / l / l210 / 1.ddi / ANSWERS.ARC / ANS_203C.PRO < prev    next >
Encoding:
Prolog Source  |  1988-06-21  |  2.2 KB  |  73 lines

  1. /*
  2.    Turbo Prolog 2.0, Answer to third Exercise on page 203.
  3.    
  4.    Copyright (c) 1986, 88 by Borland International, Inc
  5. */
  6.  
  7.  
  8. /*
  9.   The flatten program for complex lists is an
  10.   advanced technique. Please read the "Fascinating
  11.   Worlds of Lists and Recursion " and "Basic Language
  12.   Elements" in your manual.
  13.  
  14.   Complex lists are handled by the following domain
  15.   declarations. A list must have a functor as shown
  16.   and then must be declared recursively.
  17. */
  18.  
  19. Domains
  20.   element = l(list) ; s(symbol) ; i(integer) ; c(char) ; t(string) ; r(real)
  21.   list = element*
  22.  
  23. Predicates
  24.    append(list,list,list)
  25.    flatten_list(list)
  26.    flatten(list,list)
  27.  
  28. Goal
  29.  makewindow(1,2,3," Flatten ",0,0,25,80) ,
  30.  
  31.  List_to_flatten = [l([l([s(a)]) ,
  32.                     l([]) ,
  33.                     l([l([l([t("b")]),c('c')])]) ,
  34.                     l([i(4),r(5.0001)]), s(f)])] ,
  35.  
  36.  write("Flatten the list:\n\n",List_to_flatten,"\n\n") ,                    
  37.  flatten_list( List_to_flatten ) ,
  38.  write("\n\nPress any key...") ,
  39.  readchar(_).
  40.                
  41. /*
  42.  
  43.   The trick is to write the list first, then add the functors:
  44.     flatten_list( [ [ a ] , [ ] , [ [ [ b ] , c ] ] , [ d , e ] , f ]).
  45.     
  46.   Adding the functors gives the following Turbo Prolog list:
  47.    flatten_list([l([l([s(a)]) ,
  48.                 l([]) ,
  49.                 l([l([l([s(b)]),s(c)])]) ,
  50.                 l([s(d),s(e)]) ,
  51.                 s(f)])]).
  52.   
  53. */
  54. Clauses
  55.     flatten_list(List) :- 
  56.                  flatten(List, Flat_List), nl ,
  57.                  write("The list flattened is:\n\n",
  58.                        Flat_List,"\n\n"), fail;true.
  59.    
  60.     flatten([],[]).                  /* terminating clause */
  61.     
  62.     flatten([l(X)|X1], Y) :-       /* if the head of the list is a list */
  63.            flatten(X,Y1) ,           /* flatten the head of the list      */
  64.            flatten(X1,Y2) ,          /* then flatten the tail             */
  65.            append(Y1, Y2, Y).        /* append the flat head to the tail  */
  66.  
  67.     flatten([X|X1],[X|Y]) :-         /* if the head is not a list, move   */
  68.            not( X=l(_) ),
  69.            flatten(X1,Y) .           /* it to the tail; flatten the tail  */
  70.            
  71.     append([],L,L).
  72.     append([X|L1],L2,[X|L3]):-append(L1,L2,L3).
  73.