less6 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. COMMENT
  2. REDUCE INTERACTIVE LESSON NUMBER 6
  3. David R. Stoutemyer
  4. University of Hawaii
  5. COMMENT This is lesson 6 of 7 REDUCE lessons. A prerequisite is to
  6. read the phamphlet "An Introduction to LISP", by D. Lurie'.
  7. To avoid confusion between RLISP and the SYMBOLIC-mode algebraic
  8. algorithms, this lesson will treat only RLISP. Lesson 7 deals with how
  9. the REDUCE algebraic mode is implemented in RLISP and how the user can
  10. interact directly with that implementation. That is why I suggested
  11. that you run this lesson in RLISP rather than full REDUCE. If you
  12. forgot or do not have a locally available separate RLISP, then please
  13. switch now to symbolic mode by typing the statement SYMBOLIC;
  14. PAUSE;
  15. COMMENT Your most frequent mistakes are likely to be forgetting to quote
  16. data examples, using commas as separators within lists, and not puting
  17. enough levels of parentheses in your data examples.
  18. Now that you have learned from your reading about the built-in RLISP
  19. functions CAR, CDR, CONS, ATOM, EQ, NULL, LIST, APPEND, REVERSE, DELETE,
  20. MAPLIST, MAPCON, LAMBDA, FLAG, FLAGP, PUT, GET, DEFLIST, NUMBERP, ZEROP,
  21. ONEP, AND, EVAL, PLUS, TIMES, CAAR, CADR, etc., here is an opportunity
  22. to reinforce the learning by practice.: Write expressions using CAR,
  23. CDR, CDDR, etc., (which are defined only through 4 letters between C and
  24. R), to individually extract each atom from F, where;
  25. F := '((JOHN . DOE) (1147 HOTEL STREET) HONOLULU);
  26. PAUSE;
  27. COMMENT My solutions are CAAR F, CDAR F, CAADR F, CADADR F,
  28. CADDR CADR F, and CADDR F.
  29. Although commonly the "." is only mentioned in conjunction with data, we
  30. can also use it as an infix alias for CONS. Do this to build from F and
  31. from the data 'MISTER the s-expression consisting of F with MISTER
  32. inserted before JOHN.DOE;
  33. PAUSE;
  34. COMMENT My solution is ('MISTER . CAR F) . CDR F .
  35. Enough of these inane exercises -- let's get on to something useful!
  36. Let's develop a collection of functions for operating on finite sets.
  37. We will let the elements be arbitrary s-expressions, and we will
  38. represent a set as a list of its elements in arbitrary order, without
  39. duplicates.
  40. Here is a function which determines whether its first argument is a
  41. member of the set which is its second element;
  42. SYMBOLIC PROCEDURE MEMBERP(ELEM, SET1);
  43. COMMENT Returns T if s-expression ELEM is a top-level element
  44. of list SET1, returning NIL otherwise;
  45. IF NULL SET1 THEN NIL
  46. ELSE IF ELEM = CAR SET1 THEN T
  47. ELSE MEMBERP(ELEM, CDR SET1);
  48. MEMBERP('BLUE, '(RED BLUE GREEN));
  49. COMMENT This function illustrates several convenient techniques for
  50. writing functions which process lists:
  51. 1. To avoid the errors of taking the CAR or the CDR of an atom, and
  52. to build self confidence while it is not immediately apparent how to
  53. completely solve the problem, treat the trivial cases first. For an
  54. s-expression or list argument, the most trivial cases are generally
  55. when one or more of the arguments are NIL, and a slightly less
  56. trivial case is when one or more is an atom. (Note that we will get
  57. an error message if we use MEMBERP with a second argument which is
  58. not a list. We could check for this, but in the interest of brevity,
  59. I will not strive to make our set-package give set-oriented error
  60. messages.)
  61. 2. Use CAR to extract the first element and use CDR to refer to the
  62. remainder of the list.
  63. 3. Use recursion to treat more complicated cases by extracting the
  64. first element and using the same functions on smaller arguments.;
  65. PAUSE;
  66. COMMENT To make MEMBERP into an infix operator we make the declaration;
  67. INFIX MEMBERP;
  68. '(JOHN.DOE) MEMBERP '((FIG.NEWTON) FONZO (SANTA CLAUS));
  69. COMMENT Infix operators associate left, meaning expressions of the form
  70. (operator1 operator operand2 operator ... operandN)
  71. are interpreted as
  72. ((...(operand1 operator operand2) operator ... operandN).
  73. Operators may also be flagged RIGHT by
  74. FLAG ('(op1 op2 ...), 'RIGHT) .
  75. to give the interpretation
  76. (operand1 operator (operand2 operator (... operandN))...).
  77. Of the built-in operators, only ".", "*=", "+", and "*" associate right.
  78. If we had made the infix declaration before the function definition, the
  79. latter could have begun with the more natural statement
  80. SYMBOLIC PROCEDURE ELEM MEMBERP SET .
  81. Infix functions can also be referred to by functional notation if one
  82. desires. Actually, an analogous infix operator named MEMBER is already
  83. built-into RLISP, so we will use MEMBER rather than MEMBERP from here
  84. on;
  85. MEMBER(1147, CADR F);
  86. COMMENT Inspired by the simple yet elegant definition of MEMBERP, write
  87. a function named SETP which uses MEMBER to check for a duplicate element
  88. in its list argument, thus determining whether or not the argument of
  89. SETP is a set;
  90. PAUSE;
  91. COMMENT My solution is;
  92. SYMBOLIC PROCEDURE SETP CANDIDATE;
  93. COMMENT Returns T if list CANDIDATE is a set, returning NIL
  94. otherwise;
  95. IF NULL CANDIDATE THEN T
  96. ELSE IF CAR CANDIDATE MEMBER CDR CANDIDATE THEN NIL
  97. ELSE SETP CDR CANDIDATE;
  98. SETP '(KERMIT, (COOKIE MONSTER));
  99. SETP '(DOG CAT DOG);
  100. COMMENT If you used a BEGIN-block, local variables, loops, etc., then
  101. your solution is surely more awkward than mine. For the duration of the
  102. lesson, try to do everything without groups, BEGIN-blocks, local
  103. variables, assignments, and loops. Everything can be done using
  104. function composition, conditional expressions, and recursion. It will
  105. be a mind-expanding experience -- more so than transcendental
  106. meditation, psilopsybin, and EST. Afterward, you can revert to your old
  107. ways if you disagree.
  108. Thus endeth the sermon.
  109. Incidentally, to make the above definition of SETP work for non-list
  110. arguments all we have to do is insert "ELSE IF ATOM CANDIDATE THEN NIL"
  111. below "IF NULL CANDIDATE THEN T".
  112. Now try to write an infix procedure named SUBSETOF, such that SET1
  113. SUBSETOF SET2 returns NIL if SET1 contains an element that SET2 does
  114. not, returning T otherwise. You are always encouraged, by the way, to
  115. use any functions that are already builtin, or that we have previously
  116. defined, or that you define later as auxiliary functions;
  117. PAUSE;
  118. COMMENT My solution is;
  119. INFIX SUBSETOF;
  120. SYMBOLIC PROCEDURE SET1 SUBSETOF SET2;
  121. IF NULL SET1 THEN T
  122. ELSE IF CAR SET1 MEMBER SET2 THEN CDR SET1 SUBSETOF SET2
  123. ELSE NIL;
  124. '(ROOF DOOR) SUBSETOF '(WINDOW DOOR FLOOR ROOF);
  125. '(APPLE BANANA) SUBSETOF '((APPLE COBBLER) (BANANA CREME PIE));
  126. COMMENT Two sets are equal when they have identical elements, not
  127. necessarily in the same order. Write an infix procedure named
  128. EQSETP which returns T if its two operands are equal sets, returning
  129. NIL otherwise;
  130. PAUSE;
  131. COMMENT The following solution introduces the PRECEDENCE declaration;
  132. INFIX EQSETP;
  133. PRECEDENCE EQSETP, =;
  134. PRECEDENCE SUBSETOF, EQSETP;
  135. SYMBOLIC PROCEDURE SET1 EQSETP SET2;
  136. SET1 SUBSETOF SET2 AND SET2 SUBSETOF SET1;
  137. '(BALLET TAP) EQSETP '(TAP BALLET);
  138. '(PINE FIR ASPEN) EQSETP '(PINE FIR PALM);
  139. COMMENT The precedence declarations make SUBSETOF have a higher
  140. precedence than EQSETP and make the latter have higher precedence than
  141. "=", which is higher than "AND",. Consequently, these declarations
  142. enabled me to omit parentheses around "SET1 SUBSUBSETOF SET2" and around
  143. "SET2 SUBSETOF SET1". All prefix operators are higher than any infix
  144. operator, and to inspect the ordering among the latter, we merely
  145. inspect the value of the global variable named;
  146. PRECLIS!*;
  147. COMMENT Now see if you can write a REDUCE infix function named
  148. PROPERSUBSETOF, which determines if its left operand is a proper subset
  149. of its right operand, meaning it is a subset which is not equal to the
  150. right operand;
  151. PAUSE;
  152. COMMENT All of the above exercises have been predicates. In contrast,
  153. the next exercise is to write a function called MAKESET, which returns
  154. a list which is a copy of its argument, omitting duplicates;
  155. PAUSE;
  156. COMMENT How about;
  157. SYMBOLIC PROCEDURE MAKESET LIS;
  158. IF NULL LIS THEN NIL
  159. ELSE IF CAR LIS MEMBER CDR LIS THEN MAKESET CDR LIS
  160. ELSE CAR LIS . MAKESET CDR LIS;
  161. COMMENT As you may have guessed, the next exercise is to implement an
  162. operator named INTERSECT, which returns the intersection of its set
  163. operands;
  164. PAUSE;
  165. COMMENT Here is my solution;
  166. INFIX INTERSECT;
  167. PRECEDENCE INTERSECT, SUBSETOF;
  168. SYMBOLIC PROCEDURE SET1 INTERSECT SET2;
  169. IF NULL SET1 THEN NIL
  170. ELSE IF CAR SET1 MEMBER SET2
  171. THEN CAR SET1 . CDR SET1 INTERSECT SET2
  172. ELSE CDR SET1 INTERSECT SET2;
  173. COMMENT Symbolic-mode REDUCE has a built-in function named SETDIFF,
  174. which returns the set of elements which are in its first argument but
  175. not the second. See if you can write an infix definition of a similar
  176. function named DIFFSET;
  177. PAUSE;
  178. COMMENT Presenting --;
  179. INFIX DIFFSET;
  180. PRECEDENCE DIFFSET, INTERSECT;
  181. SYMBOLIC PROCEDURE LEFT DIFFSET RIGHT;
  182. IF NULL LEFT THEN NIL
  183. ELSE IF CAR LEFT MEMBER RIGHT THEN CDR LEFT DIFFSET RIGHT
  184. ELSE CAR LEFT . (CDR LEFT DIFFSET RIGHT);
  185. '(SEAGULL WREN CONDOR) DIFFSET '(WREN LARK);
  186. COMMENT The symmetric difference of two sets is the set of all elements
  187. which are in only one of the two sets. Implement a corresponding infix
  188. function named SYMDIFF. Look for the easy way! There is almost always
  189. one for examinations and instructional exercises; PAUSE;
  190. COMMENT Presenting --;
  191. INFIX SYMDIFF;
  192. PRECEDENCE SYMDIFF, INTERSECT;
  193. SYMBOLIC PROCEDURE SET1 SYMDIFF SET2;
  194. APPEND(SET1 DIFFSET SET2, SET2 DIFFSET SET1);
  195. '(SEAGULL WREN CONDOR) SYMDIFF '(WREN LARK);
  196. COMMENT We can use APPEND because the two set differences are disjoint.
  197. The above set of exercises (exercises of set?) have all returned set
  198. results. The cardinality, size, or length of a set is the number of
  199. elements in the set. More generally, it is useful to have a function
  200. which returns the length of its list argument, and such a function is
  201. built-into RLISP. See if you can write a similar function named SIZEE;
  202. PAUSE;
  203. COMMENT Presenting --;
  204. SYMBOLIC PROCEDURE SIZEE LIS;
  205. IF NULL LIS THEN 0
  206. ELSE 1 + SIZEE CDR LIS;
  207. SIZEE '(HOW MARVELOUSLY CONCISE);
  208. SIZEE '();
  209. COMMENT Literal atoms, meaning atoms which are not numbers, are stored
  210. uniquely in LISP and in RLISP, so comparison for equality of literal
  211. atoms can be implemented by comparing their addresses, which is
  212. significantly more efficient than a character-by-character comparison of
  213. their names. The comparixon operator "EQ" compares addresses, so it is
  214. the most efficient choice when comparing only literal atoms. The
  215. assignments
  216. N2 := N1 := 987654321,
  217. S2 := S1 := '(FROG (SALAMANDER.NEWT)),
  218. make N2 have the same address as N1 and make S2 have the same address as
  219. S1, but if N1 and N2 were constructed independently, they would not
  220. generally have the same address, and similarly for S1 vs S2. The
  221. comparison operator "=", which is an alias for "EQUAL", does a general
  222. test for identical s-expressions, which need not be merely two pointers
  223. to the same address. Since "=" is built-in, compiled, and crucial, I
  224. will define my own differently-named version denoted ".=" as follows:;
  225. NEWTOK '((!.!=) MYEQUAL);
  226. INFIX MYEQUAL;
  227. PRECEDENCE MYEQUAL, EQUAL;
  228. SYMBOLIC PROCEDURE S1 MYEQUAL S2;
  229. IF ATOM S1 THEN
  230. IF ATOM S2 THEN S1 EQATOM S2
  231. ELSE NIL
  232. ELSE IF ATOM S2 THEN NIL
  233. ELSE CAR S1 MYEQUAL CAR S2 AND CDR S1 MYEQUAL CDR S2;
  234. SYMBOLIC PROCEDURE A1 EQATOM A2;
  235. IF NUMBERP A1 THEN
  236. IF NUMBERP A2 THEN ZEROP(A1-A2)
  237. ELSE NIL
  238. ELSE IF NUMBERP A2 THEN NIL
  239. ELSE A1 EQ A2;
  240. COMMENT Here I introduced a help function named EQATOM, because I was
  241. beginning to become confused by detail when I got to the line which uses
  242. EQATOM. Consequently, I procrastinated on attending to some fine detail
  243. by relegating it to a help function which I was confident could be
  244. successfully written later. After completing MYEQUAL, I was confident
  245. that it would work provided EQATOM worked, so I could then turn my
  246. attention entirely to EQATOM, freed of further distraction by concern
  247. about the more ambitious overall goal. It turns out that EQATOM is a
  248. rather handy utility function anyway, and practice helps develop good
  249. judgement about where best to so subdivide tasks. This psychological
  250. divide-and-conquer programming technique is important in most other
  251. programming languages too.
  252. ".=" is differnt from our previous examples in that ".=" recurses down
  253. the CAR as well as down the CDR of an s-expression;
  254. PAUSE;
  255. COMMENT
  256. If a list has n elements, our function named MEMBERP or the equivalent
  257. built-in function named MEMBER requires on the order of n "=" tests.
  258. Consequently, the above definitions of SETP and MAKESET, which require
  259. on the order of n membership tests, will require on the order of n**2
  260. "=" tests. Similarly, if the two operands have m and n elements, the
  261. above definitions of SUBSETOF, EQSETP, INTERSECT, DIFFSET, and
  262. SYMDIFF require on the order of m*n "=" tests. We could decrease the
  263. growth rates to order of n and order of m+n respectively by sorting the
  264. elements before giving lists to these functions. The best algorithms
  265. sort a list of n elements in the order of n*log(n) element comparisons,
  266. and this need be done only once per input set. To do so we need a
  267. function which returns T if the first arguemtn is "=" to the second
  268. argument or should be placed to the left of the second argument. Such a
  269. function, named ORDP, is already built-into symbolic-mode REDUCE, based
  270. on the following rules:
  271. 1. Any number orders left of NIL.
  272. 2. Larger numbers order left of smaller numbers.
  273. 4. Literal atoms order left of numbers.
  274. 3. Literal atoms order among themselves by address, as determined
  275. by the built-in RLISP function named ORDERP.
  276. 5. Non-atoms order left of atoms.
  277. 6. Non-atoms order among themselves according to ORDP of their
  278. CARs, with ties broken according to ORDP of their CDRs.
  279. Try writing an analogous function named MYORD, and, if you are in
  280. REDUCE rather than RLISP, test its behaviour in comparison to ORDP;
  281. PAUSE;
  282. COMMENT Whether or not we use sorted sets, we can reduce the
  283. proportionality constant associated with the growth rate by replacing
  284. "=" by "EQ" if the set elements are restricted to literal atoms.
  285. However, with such elements we can use property-lists to achieve the
  286. growth rates of the sorted algorithms without any need to sort the
  287. sets. On any LISP system that is efficient enough to support REDUCE
  288. with acceptable performance, the time required sto access a property of
  289. an atome is modest and very insensitive to the number of distinct
  290. atoms in the program and data. Consequently, the basic technique
  291. for any of our set operations is:
  292. 1. Scan the list argument or one of the two list arguments,
  293. flagging each element as "SEEN".
  294. 2. During the first scan, or during a second scan of the same
  295. list, or during a scan of the second list, check each element
  296. to see whether or not it has already been flagged, and act
  297. accordingly.
  298. 3. Make a final pass through all elements which were flagged to
  299. remove the flag "SEEN". (Otherwise, we may invalidate later set
  300. operations which utilize any of the same atoms.)
  301. We could use indicators rather than flags, but the latter are slightly
  302. more efficient when an indicator would have only one value (such as
  303. having "SEEN" as the value of an indicator named "SEENORNOT").
  304. As an example, here is INTERSECT defined using this technique;
  305. SYMBOLIC PROCEDURE INTERSECT(S1, S2);
  306. BEGIN SCALAR ANS, SET2;
  307. FLAG(S1, 'SEEN);
  308. SET2 := S2;
  309. WHILE SET2 DO <<
  310. IF FLAGP(CAR SET2, 'SEEN) THEN ANS := CAR SET2 . ANS;
  311. SET2 := CDR SET2 >>;
  312. REMFLAG(S1, 'SEEN);
  313. RETURN ANS
  314. END;
  315. COMMENT Perhaps you noticed that, having used a BEGIN-block, group,
  316. loop, and assignments, I have not practiced what I preached about
  317. using only function composition, conditional expressions, and
  318. recursion during this lesson. Well, now that you have had some
  319. exposure to both extremes, I think you should always fairly
  320. consider both together with appropriate compromises, in each case
  321. choosing whatever is most clear, concise, and natural. For set
  322. operations based on the property-list approach, I find the style
  323. exemplified immediately above most natural.
  324. As your last exercise for this lesson, develop a file containing a
  325. package for set operations based upon either property-lists or sorting.
  326. This is the end of lesson 6. When you are ready to run the final lesson
  327. 7, load a fresh copy of REDUCE.
  328. ;END;