LESS6 16 KB

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