srfi-1.scm 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641
  1. ;;; SRFI-1 list-processing library -*- Scheme -*-
  2. ;;; Reference implementation
  3. ;;;
  4. ;;; Copyright (c) 1998, 1999 by Olin Shivers. You may do as you please with
  5. ;;; this code as long as you do not remove this copyright notice or
  6. ;;; hold me liable for its use. Please send bug reports to shivers@ai.mit.edu.
  7. ;;; -Olin
  8. ; Changes made for Scheme 48
  9. ;
  10. ; - CHECK-ARG is defined as a macro that does nothing.
  11. ; - replaced the one use of LET-OPTIONAL
  12. ; - added definition of :OPTIONAL
  13. (define-syntax check-arg
  14. (syntax-rules ()
  15. ((check-arg stuff ...) #f)))
  16. (define (:optional maybe-value default)
  17. (cond ((null? maybe-value)
  18. default)
  19. ((null? (cdr maybe-value))
  20. (car maybe-value))
  21. (else
  22. (error "too many arguments passed to :optional" maybe-value))))
  23. ;;; This is a library of list- and pair-processing functions. I wrote it after
  24. ;;; carefully considering the functions provided by the libraries found in
  25. ;;; R4RS/R5RS Scheme, MIT Scheme, Gambit, RScheme, MzScheme, slib, Common
  26. ;;; Lisp, Bigloo, guile, T, APL and the SML standard basis. It is a pretty
  27. ;;; rich toolkit, providing a superset of the functionality found in any of
  28. ;;; the various Schemes I considered.
  29. ;;; This implementation is intended as a portable reference implementation
  30. ;;; for SRFI-1. See the porting notes below for more information.
  31. ;;; Exported:
  32. ;;; xcons tree-copy make-list list-tabulate cons* list-copy
  33. ;;; proper-list? circular-list? dotted-list? not-pair? null-list? list=
  34. ;;; circular-list length+
  35. ;;; iota
  36. ;;; first second third fourth fifth sixth seventh eighth ninth tenth
  37. ;;; car+cdr
  38. ;;; take drop
  39. ;;; take-right drop-right
  40. ;;; take! drop-right!
  41. ;;; split-at split-at!
  42. ;;; last last-pair
  43. ;;; zip unzip1 unzip2 unzip3 unzip4 unzip5
  44. ;;; count
  45. ;;; append! append-reverse append-reverse! concatenate concatenate!
  46. ;;; unfold fold pair-fold reduce
  47. ;;; unfold-right fold-right pair-fold-right reduce-right
  48. ;;; append-map append-map! map! pair-for-each filter-map map-in-order
  49. ;;; filter partition remove
  50. ;;; filter! partition! remove!
  51. ;;; find find-tail any every list-index
  52. ;;; take-while drop-while take-while!
  53. ;;; span break span! break!
  54. ;;; delete delete!
  55. ;;; alist-cons alist-copy
  56. ;;; delete-duplicates delete-duplicates!
  57. ;;; alist-delete alist-delete!
  58. ;;; reverse!
  59. ;;; lset<= lset= lset-adjoin
  60. ;;; lset-union lset-intersection lset-difference lset-xor lset-diff+intersection
  61. ;;; lset-union! lset-intersection! lset-difference! lset-xor! lset-diff+intersection!
  62. ;;;
  63. ;;; In principle, the following R4RS list- and pair-processing procedures
  64. ;;; are also part of this package's exports, although they are not defined
  65. ;;; in this file:
  66. ;;; Primitives: cons pair? null? car cdr set-car! set-cdr!
  67. ;;; Non-primitives: list length append reverse cadr ... cddddr list-ref
  68. ;;; memq memv assq assv
  69. ;;; (The non-primitives are defined in this file, but commented out.)
  70. ;;;
  71. ;;; These R4RS procedures have extended definitions in SRFI-1 and are defined
  72. ;;; in this file:
  73. ;;; map for-each member assoc
  74. ;;;
  75. ;;; The remaining two R4RS list-processing procedures are not included:
  76. ;;; list-tail (use drop)
  77. ;;; list? (use proper-list?)
  78. ;;; A note on recursion and iteration/reversal:
  79. ;;; Many iterative list-processing algorithms naturally compute the elements
  80. ;;; of the answer list in the wrong order (left-to-right or head-to-tail) from
  81. ;;; the order needed to cons them into the proper answer (right-to-left, or
  82. ;;; tail-then-head). One style or idiom of programming these algorithms, then,
  83. ;;; loops, consing up the elements in reverse order, then destructively
  84. ;;; reverses the list at the end of the loop. I do not do this. The natural
  85. ;;; and efficient way to code these algorithms is recursively. This trades off
  86. ;;; intermediate temporary list structure for intermediate temporary stack
  87. ;;; structure. In a stack-based system, this improves cache locality and
  88. ;;; lightens the load on the GC system. Don't stand on your head to iterate!
  89. ;;; Recurse, where natural. Multiple-value returns make this even more
  90. ;;; convenient, when the recursion/iteration has multiple state values.
  91. ;;; Porting:
  92. ;;; This is carefully tuned code; do not modify casually.
  93. ;;; - It is careful to share storage when possible;
  94. ;;; - Side-effecting code tries not to perform redundant writes.
  95. ;;;
  96. ;;; That said, a port of this library to a specific Scheme system might wish
  97. ;;; to tune this code to exploit particulars of the implementation.
  98. ;;; The single most important compiler-specific optimisation you could make
  99. ;;; to this library would be to add rewrite rules or transforms to:
  100. ;;; - transform applications of n-ary procedures (e.g. LIST=, CONS*, APPEND,
  101. ;;; LSET-UNION) into multiple applications of a primitive two-argument
  102. ;;; variant.
  103. ;;; - transform applications of the mapping functions (MAP, FOR-EACH, FOLD,
  104. ;;; ANY, EVERY) into open-coded loops. The killer here is that these
  105. ;;; functions are n-ary. Handling the general case is quite inefficient,
  106. ;;; requiring many intermediate data structures to be allocated and
  107. ;;; discarded.
  108. ;;; - transform applications of procedures that take optional arguments
  109. ;;; into calls to variants that do not take optional arguments. This
  110. ;;; eliminates unnecessary consing and parsing of the rest parameter.
  111. ;;;
  112. ;;; These transforms would provide BIG speedups. In particular, the n-ary
  113. ;;; mapping functions are particularly slow and cons-intensive, and are good
  114. ;;; candidates for tuning. I have coded fast paths for the single-list cases,
  115. ;;; but what you really want to do is exploit the fact that the compiler
  116. ;;; usually knows how many arguments are being passed to a particular
  117. ;;; application of these functions -- they are usually explicitly called, not
  118. ;;; passed around as higher-order values. If you can arrange to have your
  119. ;;; compiler produce custom code or custom linkages based on the number of
  120. ;;; arguments in the call, you can speed these functions up a *lot*. But this
  121. ;;; kind of compiler technology no longer exists in the Scheme world as far as
  122. ;;; I can see.
  123. ;;;
  124. ;;; Note that this code is, of course, dependent upon standard bindings for
  125. ;;; the R5RS procedures -- i.e., it assumes that the variable CAR is bound
  126. ;;; to the procedure that takes the car of a list. If your Scheme
  127. ;;; implementation allows user code to alter the bindings of these procedures
  128. ;;; in a manner that would be visible to these definitions, then there might
  129. ;;; be trouble. You could consider horrible kludgery along the lines of
  130. ;;; (define fact
  131. ;;; (let ((= =) (- -) (* *))
  132. ;;; (letrec ((real-fact (lambda (n)
  133. ;;; (if (= n 0) 1 (* n (real-fact (- n 1)))))))
  134. ;;; real-fact)))
  135. ;;; Or you could consider shifting to a reasonable Scheme system that, say,
  136. ;;; has a module system protecting code from this kind of lossage.
  137. ;;;
  138. ;;; This code does a fair amount of run-time argument checking. If your
  139. ;;; Scheme system has a sophisticated compiler that can eliminate redundant
  140. ;;; error checks, this is no problem. However, if not, these checks incur
  141. ;;; some performance overhead -- and, in a safe Scheme implementation, they
  142. ;;; are in some sense redundant: if we don't check to see that the PROC
  143. ;;; parameter is a procedure, we'll find out anyway three lines later when
  144. ;;; we try to call the value. It's pretty easy to rip all this argument
  145. ;;; checking code out if it's inappropriate for your implementation -- just
  146. ;;; nuke every call to CHECK-ARG.
  147. ;;;
  148. ;;; On the other hand, if you *do* have a sophisticated compiler that will
  149. ;;; actually perform soft-typing and eliminate redundant checks (Rice's systems
  150. ;;; being the only possible candidate of which I'm aware), leaving these checks
  151. ;;; in can *help*, since their presence can be elided in redundant cases,
  152. ;;; and in cases where they are needed, performing the checks early, at
  153. ;;; procedure entry, can "lift" a check out of a loop.
  154. ;;;
  155. ;;; Finally, I have only checked the properties that can portably be checked
  156. ;;; with R5RS Scheme -- and this is not complete. You may wish to alter
  157. ;;; the CHECK-ARG parameter checks to perform extra, implementation-specific
  158. ;;; checks, such as procedure arity for higher-order values.
  159. ;;;
  160. ;;; The code has only these non-R4RS dependencies:
  161. ;;; A few calls to an ERROR procedure;
  162. ;;; Uses of the R5RS multiple-value procedure VALUES and the m-v binding
  163. ;;; RECEIVE macro (which isn't R5RS, but is a trivial macro).
  164. ;;; Many calls to a parameter-checking procedure check-arg:
  165. ;;; (define (check-arg pred val caller)
  166. ;;; (let lp ((val val))
  167. ;;; (if (pred val) val (lp (error "Bad argument" val pred caller)))))
  168. ;;; A few uses of the LET-OPTIONAL and :OPTIONAL macros for parsing
  169. ;;; optional arguments.
  170. ;;;
  171. ;;; Most of these procedures use the NULL-LIST? test to trigger the
  172. ;;; base case in the inner loop or recursion. The NULL-LIST? function
  173. ;;; is defined to be a careful one -- it raises an error if passed a
  174. ;;; non-nil, non-pair value. The spec allows an implementation to use
  175. ;;; a less-careful implementation that simply defines NULL-LIST? to
  176. ;;; be NOT-PAIR?. This would speed up the inner loops of these procedures
  177. ;;; at the expense of having them silently accept dotted lists.
  178. ;;; A note on dotted lists:
  179. ;;; I, personally, take the view that the only consistent view of lists
  180. ;;; in Scheme is the view that *everything* is a list -- values such as
  181. ;;; 3 or "foo" or 'bar are simply empty dotted lists. This is due to the
  182. ;;; fact that Scheme actually has no true list type. It has a pair type,
  183. ;;; and there is an *interpretation* of the trees built using this type
  184. ;;; as lists.
  185. ;;;
  186. ;;; I lobbied to have these list-processing procedures hew to this
  187. ;;; view, and accept any value as a list argument. I was overwhelmingly
  188. ;;; overruled during the SRFI discussion phase. So I am inserting this
  189. ;;; text in the reference lib and the SRFI spec as a sort of "minority
  190. ;;; opinion" dissent.
  191. ;;;
  192. ;;; Many of the procedures in this library can be trivially redefined
  193. ;;; to handle dotted lists, just by changing the NULL-LIST? base-case
  194. ;;; check to NOT-PAIR?, meaning that any non-pair value is taken to be
  195. ;;; an empty list. For most of these procedures, that's all that is
  196. ;;; required.
  197. ;;;
  198. ;;; However, we have to do a little more work for some procedures that
  199. ;;; *produce* lists from other lists. Were we to extend these procedures to
  200. ;;; accept dotted lists, we would have to define how they terminate the lists
  201. ;;; produced as results when passed a dotted list. I designed a coherent set
  202. ;;; of termination rules for these cases; this was posted to the SRFI-1
  203. ;;; discussion list. I additionally wrote an earlier version of this library
  204. ;;; that implemented that spec. It has been discarded during later phases of
  205. ;;; the definition and implementation of this library.
  206. ;;;
  207. ;;; The argument *against* defining these procedures to work on dotted
  208. ;;; lists is that dotted lists are the rare, odd case, and that by
  209. ;;; arranging for the procedures to handle them, we lose error checking
  210. ;;; in the cases where a dotted list is passed by accident -- e.g., when
  211. ;;; the programmer swaps a two arguments to a list-processing function,
  212. ;;; one being a scalar and one being a list. For example,
  213. ;;; (member '(1 3 5 7 9) 7)
  214. ;;; This would quietly return #f if we extended MEMBER to accept dotted
  215. ;;; lists.
  216. ;;;
  217. ;;; The SRFI discussion record contains more discussion on this topic.
  218. ;;; Constructors
  219. ;;;;;;;;;;;;;;;;
  220. ;;; Occasionally useful as a value to be passed to a fold or other
  221. ;;; higher-order procedure.
  222. (define (xcons d a) (cons a d))
  223. ;;;; Recursively copy every cons.
  224. ;(define (tree-copy x)
  225. ; (let recur ((x x))
  226. ; (if (not (pair? x)) x
  227. ; (cons (recur (car x)) (recur (cdr x))))))
  228. ;;; Make a list of length LEN.
  229. (define (make-list len . maybe-elt)
  230. (check-arg (lambda (n) (and (integer? n) (>= n 0))) len make-list)
  231. (let ((elt (cond ((null? maybe-elt) #f) ; Default value
  232. ((null? (cdr maybe-elt)) (car maybe-elt))
  233. (else (error "Too many arguments to MAKE-LIST"
  234. (cons len maybe-elt))))))
  235. (do ((i len (- i 1))
  236. (ans '() (cons elt ans)))
  237. ((<= i 0) ans))))
  238. ;(define (list . ans) ans) ; R4RS
  239. ;;; Make a list of length LEN. Elt i is (PROC i) for 0 <= i < LEN.
  240. (define (list-tabulate len proc)
  241. (check-arg (lambda (n) (and (integer? n) (>= n 0))) len list-tabulate)
  242. (check-arg procedure? proc list-tabulate)
  243. (do ((i (- len 1) (- i 1))
  244. (ans '() (cons (proc i) ans)))
  245. ((< i 0) ans)))
  246. ;;; (cons* a1 a2 ... an) = (cons a1 (cons a2 (cons ... an)))
  247. ;;; (cons* a1) = a1 (cons* a1 a2 ...) = (cons a1 (cons* a2 ...))
  248. ;;;
  249. ;;; (cons first (unfold not-pair? car cdr rest values))
  250. (define (cons* first . rest)
  251. (let recur ((x first) (rest rest))
  252. (if (pair? rest)
  253. (cons x (recur (car rest) (cdr rest)))
  254. x)))
  255. ;;; (unfold not-pair? car cdr lis values)
  256. (define (list-copy lis)
  257. (let recur ((lis lis))
  258. (if (pair? lis)
  259. (cons (car lis) (recur (cdr lis)))
  260. lis)))
  261. ;;; IOTA count [start step] (start start+step ... start+(count-1)*step)
  262. (define (iota count . maybe-start+step)
  263. (check-arg integer? count iota)
  264. (if (< count 0) (error "Negative step count" iota count))
  265. ; (let-optionals maybe-start+step ((start 0) (step 1)) ...)
  266. (receive (start step)
  267. (case (length maybe-start+step)
  268. ((0) (values 0 1))
  269. ((2) (values (car maybe-start+step)
  270. (cadr maybe-start+step)))
  271. (else
  272. (error "wrong number of arguments to IOTA"
  273. (cons count maybe-start+step))))
  274. (check-arg number? start iota)
  275. (check-arg number? step iota)
  276. (let ((last-val (+ start (* (- count 1) step))))
  277. (do ((count count (- count 1))
  278. (val last-val (- val step))
  279. (ans '() (cons val ans)))
  280. ((<= count 0) ans)))))
  281. ;;; I thought these were lovely, but the public at large did not share my
  282. ;;; enthusiasm...
  283. ;;; :IOTA to (0 ... to-1)
  284. ;;; :IOTA from to (from ... to-1)
  285. ;;; :IOTA from to step (from from+step ...)
  286. ;;; IOTA: to (1 ... to)
  287. ;;; IOTA: from to (from+1 ... to)
  288. ;;; IOTA: from to step (from+step from+2step ...)
  289. ;(define (%parse-iota-args arg1 rest-args proc)
  290. ; (let ((check (lambda (n) (check-arg integer? n proc))))
  291. ; (check arg1)
  292. ; (if (pair? rest-args)
  293. ; (let ((arg2 (check (car rest-args)))
  294. ; (rest (cdr rest-args)))
  295. ; (if (pair? rest)
  296. ; (let ((arg3 (check (car rest)))
  297. ; (rest (cdr rest)))
  298. ; (if (pair? rest) (error "Too many parameters" proc arg1 rest-args)
  299. ; (values arg1 arg2 arg3)))
  300. ; (values arg1 arg2 1)))
  301. ; (values 0 arg1 1))))
  302. ;
  303. ;(define (iota: arg1 . rest-args)
  304. ; (receive (from to step) (%parse-iota-args arg1 rest-args iota:)
  305. ; (let* ((numsteps (floor (/ (- to from) step)))
  306. ; (last-val (+ from (* step numsteps))))
  307. ; (if (< numsteps 0) (error "Negative step count" iota: from to step))
  308. ; (do ((steps-left numsteps (- steps-left 1))
  309. ; (val last-val (- val step))
  310. ; (ans '() (cons val ans)))
  311. ; ((<= steps-left 0) ans)))))
  312. ;
  313. ;
  314. ;(define (:iota arg1 . rest-args)
  315. ; (receive (from to step) (%parse-iota-args arg1 rest-args :iota)
  316. ; (let* ((numsteps (ceiling (/ (- to from) step)))
  317. ; (last-val (+ from (* step (- numsteps 1)))))
  318. ; (if (< numsteps 0) (error "Negative step count" :iota from to step))
  319. ; (do ((steps-left numsteps (- steps-left 1))
  320. ; (val last-val (- val step))
  321. ; (ans '() (cons val ans)))
  322. ; ((<= steps-left 0) ans)))))
  323. (define (circular-list val1 . vals)
  324. (let ((ans (cons val1 vals)))
  325. (set-cdr! (last-pair ans) ans)
  326. ans))
  327. ;;; <proper-list> ::= () ; Empty proper list
  328. ;;; | (cons <x> <proper-list>) ; Proper-list pair
  329. ;;; Note that this definition rules out circular lists -- and this
  330. ;;; function is required to detect this case and return false.
  331. (define (proper-list? x)
  332. (let lp ((x x) (lag x))
  333. (if (pair? x)
  334. (let ((x (cdr x)))
  335. (if (pair? x)
  336. (let ((x (cdr x))
  337. (lag (cdr lag)))
  338. (and (not (eq? x lag)) (lp x lag)))
  339. (null? x)))
  340. (null? x))))
  341. ;;; A dotted list is a finite list (possibly of length 0) terminated
  342. ;;; by a non-nil value. Any non-cons, non-nil value (e.g., "foo" or 5)
  343. ;;; is a dotted list of length 0.
  344. ;;;
  345. ;;; <dotted-list> ::= <non-nil,non-pair> ; Empty dotted list
  346. ;;; | (cons <x> <dotted-list>) ; Proper-list pair
  347. (define (dotted-list? x)
  348. (let lp ((x x) (lag x))
  349. (if (pair? x)
  350. (let ((x (cdr x)))
  351. (if (pair? x)
  352. (let ((x (cdr x))
  353. (lag (cdr lag)))
  354. (and (not (eq? x lag)) (lp x lag)))
  355. (not (null? x))))
  356. (not (null? x)))))
  357. (define (circular-list? x)
  358. (let lp ((x x) (lag x))
  359. (and (pair? x)
  360. (let ((x (cdr x)))
  361. (and (pair? x)
  362. (let ((x (cdr x))
  363. (lag (cdr lag)))
  364. (or (eq? x lag) (lp x lag))))))))
  365. (define (not-pair? x) (not (pair? x))) ; Inline me.
  366. ;;; This is a legal definition which is fast and sloppy:
  367. ;;; (define null-list? not-pair?)
  368. ;;; but we'll provide a more careful one:
  369. (define (null-list? l)
  370. (cond ((pair? l) #f)
  371. ((null? l) #t)
  372. (else (error "null-list?: argument out of domain" l))))
  373. (define (list= = . lists)
  374. (or (null? lists) ; special case
  375. (let lp1 ((list-a (car lists)) (others (cdr lists)))
  376. (or (null? others)
  377. (let ((list-b (car others))
  378. (others (cdr others)))
  379. (if (eq? list-a list-b) ; EQ? => LIST=
  380. (lp1 list-b others)
  381. (let lp2 ((list-a list-a) (list-b list-b))
  382. (if (null-list? list-a)
  383. (and (null-list? list-b)
  384. (lp1 list-b others))
  385. (and (not (null-list? list-b))
  386. (= (car list-a) (car list-b))
  387. (lp2 (cdr list-a) (cdr list-b)))))))))))
  388. ;;; R4RS, so commented out.
  389. ;(define (length x) ; LENGTH may diverge or
  390. ; (let lp ((x x) (len 0)) ; raise an error if X is
  391. ; (if (pair? x) ; a circular list. This version
  392. ; (lp (cdr x) (+ len 1)) ; diverges.
  393. ; len)))
  394. (define (length+ x) ; Returns #f if X is circular.
  395. (let lp ((x x) (lag x) (len 0))
  396. (if (pair? x)
  397. (let ((x (cdr x))
  398. (len (+ len 1)))
  399. (if (pair? x)
  400. (let ((x (cdr x))
  401. (lag (cdr lag))
  402. (len (+ len 1)))
  403. (and (not (eq? x lag)) (lp x lag len)))
  404. len))
  405. len)))
  406. (define (zip list1 . more-lists) (apply map list list1 more-lists))
  407. ;;; Selectors
  408. ;;;;;;;;;;;;;
  409. ;;; R4RS non-primitives:
  410. ;(define (caar x) (car (car x)))
  411. ;(define (cadr x) (car (cdr x)))
  412. ;(define (cdar x) (cdr (car x)))
  413. ;(define (cddr x) (cdr (cdr x)))
  414. ;
  415. ;(define (caaar x) (caar (car x)))
  416. ;(define (caadr x) (caar (cdr x)))
  417. ;(define (cadar x) (cadr (car x)))
  418. ;(define (caddr x) (cadr (cdr x)))
  419. ;(define (cdaar x) (cdar (car x)))
  420. ;(define (cdadr x) (cdar (cdr x)))
  421. ;(define (cddar x) (cddr (car x)))
  422. ;(define (cdddr x) (cddr (cdr x)))
  423. ;
  424. ;(define (caaaar x) (caaar (car x)))
  425. ;(define (caaadr x) (caaar (cdr x)))
  426. ;(define (caadar x) (caadr (car x)))
  427. ;(define (caaddr x) (caadr (cdr x)))
  428. ;(define (cadaar x) (cadar (car x)))
  429. ;(define (cadadr x) (cadar (cdr x)))
  430. ;(define (caddar x) (caddr (car x)))
  431. ;(define (cadddr x) (caddr (cdr x)))
  432. ;(define (cdaaar x) (cdaar (car x)))
  433. ;(define (cdaadr x) (cdaar (cdr x)))
  434. ;(define (cdadar x) (cdadr (car x)))
  435. ;(define (cdaddr x) (cdadr (cdr x)))
  436. ;(define (cddaar x) (cddar (car x)))
  437. ;(define (cddadr x) (cddar (cdr x)))
  438. ;(define (cdddar x) (cdddr (car x)))
  439. ;(define (cddddr x) (cdddr (cdr x)))
  440. (define first car)
  441. (define second cadr)
  442. (define third caddr)
  443. (define fourth cadddr)
  444. (define (fifth x) (car (cddddr x)))
  445. (define (sixth x) (cadr (cddddr x)))
  446. (define (seventh x) (caddr (cddddr x)))
  447. (define (eighth x) (cadddr (cddddr x)))
  448. (define (ninth x) (car (cddddr (cddddr x))))
  449. (define (tenth x) (cadr (cddddr (cddddr x))))
  450. (define (car+cdr pair) (values (car pair) (cdr pair)))
  451. ;;; take & drop
  452. (define (take lis k)
  453. (check-arg integer? k take)
  454. (let recur ((lis lis) (k k))
  455. (if (zero? k) '()
  456. (cons (car lis)
  457. (recur (cdr lis) (- k 1))))))
  458. (define (drop lis k)
  459. (check-arg integer? k drop)
  460. (let iter ((lis lis) (k k))
  461. (if (zero? k) lis (iter (cdr lis) (- k 1)))))
  462. (define (take! lis k)
  463. (check-arg integer? k take!)
  464. (if (zero? k) '()
  465. (begin (set-cdr! (drop lis (- k 1)) '())
  466. lis)))
  467. ;;; TAKE-RIGHT and DROP-RIGHT work by getting two pointers into the list,
  468. ;;; off by K, then chasing down the list until the lead pointer falls off
  469. ;;; the end.
  470. (define (take-right lis k)
  471. (check-arg integer? k take-right)
  472. (let lp ((lag lis) (lead (drop lis k)))
  473. (if (pair? lead)
  474. (lp (cdr lag) (cdr lead))
  475. lag)))
  476. (define (drop-right lis k)
  477. (check-arg integer? k drop-right)
  478. (let recur ((lag lis) (lead (drop lis k)))
  479. (if (pair? lead)
  480. (cons (car lag) (recur (cdr lag) (cdr lead)))
  481. '())))
  482. ;;; In this function, LEAD is actually K+1 ahead of LAG. This lets
  483. ;;; us stop LAG one step early, in time to smash its cdr to ().
  484. (define (drop-right! lis k)
  485. (check-arg integer? k drop-right!)
  486. (let ((lead (drop lis k)))
  487. (if (pair? lead)
  488. (let lp ((lag lis) (lead (cdr lead))) ; Standard case
  489. (if (pair? lead)
  490. (lp (cdr lag) (cdr lead))
  491. (begin (set-cdr! lag '())
  492. lis)))
  493. '()))) ; Special case dropping everything -- no cons to side-effect.
  494. ;(define (list-ref lis i) (car (drop lis i))) ; R4RS
  495. ;;; These use the APL convention, whereby negative indices mean
  496. ;;; "from the right." I liked them, but they didn't win over the
  497. ;;; SRFI reviewers.
  498. ;;; K >= 0: Take and drop K elts from the front of the list.
  499. ;;; K <= 0: Take and drop -K elts from the end of the list.
  500. ;(define (take lis k)
  501. ; (check-arg integer? k take)
  502. ; (if (negative? k)
  503. ; (list-tail lis (+ k (length lis)))
  504. ; (let recur ((lis lis) (k k))
  505. ; (if (zero? k) '()
  506. ; (cons (car lis)
  507. ; (recur (cdr lis) (- k 1)))))))
  508. ;
  509. ;(define (drop lis k)
  510. ; (check-arg integer? k drop)
  511. ; (if (negative? k)
  512. ; (let recur ((lis lis) (nelts (+ k (length lis))))
  513. ; (if (zero? nelts) '()
  514. ; (cons (car lis)
  515. ; (recur (cdr lis) (- nelts 1)))))
  516. ; (list-tail lis k)))
  517. ;
  518. ;
  519. ;(define (take! lis k)
  520. ; (check-arg integer? k take!)
  521. ; (cond ((zero? k) '())
  522. ; ((positive? k)
  523. ; (set-cdr! (list-tail lis (- k 1)) '())
  524. ; lis)
  525. ; (else (list-tail lis (+ k (length lis))))))
  526. ;
  527. ;(define (drop! lis k)
  528. ; (check-arg integer? k drop!)
  529. ; (if (negative? k)
  530. ; (let ((nelts (+ k (length lis))))
  531. ; (if (zero? nelts) '()
  532. ; (begin (set-cdr! (list-tail lis (- nelts 1)) '())
  533. ; lis)))
  534. ; (list-tail lis k)))
  535. (define (split-at x k)
  536. (check-arg integer? k split-at)
  537. (let recur ((lis x) (k k))
  538. (if (zero? k) (values '() lis)
  539. (receive (prefix suffix) (recur (cdr lis) (- k 1))
  540. (values (cons (car lis) prefix) suffix)))))
  541. (define (split-at! x k)
  542. (check-arg integer? k split-at!)
  543. (if (zero? k) (values '() x)
  544. (let* ((prev (drop x (- k 1)))
  545. (suffix (cdr prev)))
  546. (set-cdr! prev '())
  547. (values x suffix))))
  548. (define (last lis) (car (last-pair lis)))
  549. (define (last-pair lis)
  550. (check-arg pair? lis last-pair)
  551. (let lp ((lis lis))
  552. (let ((tail (cdr lis)))
  553. (if (pair? tail) (lp tail) lis))))
  554. ;;; Unzippers -- 1 through 5
  555. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  556. (define (unzip1 lis) (map car lis))
  557. (define (unzip2 lis)
  558. (let recur ((lis lis))
  559. (if (null-list? lis) (values lis lis) ; Use NOT-PAIR? to handle
  560. (let ((elt (car lis))) ; dotted lists.
  561. (receive (a b) (recur (cdr lis))
  562. (values (cons (car elt) a)
  563. (cons (cadr elt) b)))))))
  564. (define (unzip3 lis)
  565. (let recur ((lis lis))
  566. (if (null-list? lis) (values lis lis lis)
  567. (let ((elt (car lis)))
  568. (receive (a b c) (recur (cdr lis))
  569. (values (cons (car elt) a)
  570. (cons (cadr elt) b)
  571. (cons (caddr elt) c)))))))
  572. (define (unzip4 lis)
  573. (let recur ((lis lis))
  574. (if (null-list? lis) (values lis lis lis lis)
  575. (let ((elt (car lis)))
  576. (receive (a b c d) (recur (cdr lis))
  577. (values (cons (car elt) a)
  578. (cons (cadr elt) b)
  579. (cons (caddr elt) c)
  580. (cons (cadddr elt) d)))))))
  581. (define (unzip5 lis)
  582. (let recur ((lis lis))
  583. (if (null-list? lis) (values lis lis lis lis lis)
  584. (let ((elt (car lis)))
  585. (receive (a b c d e) (recur (cdr lis))
  586. (values (cons (car elt) a)
  587. (cons (cadr elt) b)
  588. (cons (caddr elt) c)
  589. (cons (cadddr elt) d)
  590. (cons (car (cddddr elt)) e)))))))
  591. ;;; append! append-reverse append-reverse! concatenate concatenate!
  592. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  593. (define (append! . lists)
  594. ;; First, scan through lists looking for a non-empty one.
  595. (let lp ((lists lists) (prev '()))
  596. (if (not (pair? lists)) prev
  597. (let ((first (car lists))
  598. (rest (cdr lists)))
  599. (if (not (pair? first)) (lp rest first)
  600. ;; Now, do the splicing.
  601. (let lp2 ((tail-cons (last-pair first))
  602. (rest rest))
  603. (if (pair? rest)
  604. (let ((next (car rest))
  605. (rest (cdr rest)))
  606. (set-cdr! tail-cons next)
  607. (lp2 (if (pair? next) (last-pair next) tail-cons)
  608. rest))
  609. first)))))))
  610. ;;; APPEND is R4RS.
  611. ;(define (append . lists)
  612. ; (if (pair? lists)
  613. ; (let recur ((list1 (car lists)) (lists (cdr lists)))
  614. ; (if (pair? lists)
  615. ; (let ((tail (recur (car lists) (cdr lists))))
  616. ; (fold-right cons tail list1)) ; Append LIST1 & TAIL.
  617. ; list1))
  618. ; '()))
  619. ;(define (append-reverse rev-head tail) (fold cons tail rev-head))
  620. ;(define (append-reverse! rev-head tail)
  621. ; (pair-fold (lambda (pair tail) (set-cdr! pair tail) pair)
  622. ; tail
  623. ; rev-head))
  624. ;;; Hand-inline the FOLD and PAIR-FOLD ops for speed.
  625. (define (append-reverse rev-head tail)
  626. (let lp ((rev-head rev-head) (tail tail))
  627. (if (null-list? rev-head) tail
  628. (lp (cdr rev-head) (cons (car rev-head) tail)))))
  629. (define (append-reverse! rev-head tail)
  630. (let lp ((rev-head rev-head) (tail tail))
  631. (if (null-list? rev-head) tail
  632. (let ((next-rev (cdr rev-head)))
  633. (set-cdr! rev-head tail)
  634. (lp next-rev rev-head)))))
  635. (define (concatenate lists) (reduce-right append '() lists))
  636. (define (concatenate! lists) (reduce-right append! '() lists))
  637. ;;; Fold/map internal utilities
  638. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  639. ;;; These little internal utilities are used by the general
  640. ;;; fold & mapper funs for the n-ary cases . It'd be nice if they got inlined.
  641. ;;; One the other hand, the n-ary cases are painfully inefficient as it is.
  642. ;;; An aggressive implementation should simply re-write these functions
  643. ;;; for raw efficiency; I have written them for as much clarity, portability,
  644. ;;; and simplicity as can be achieved.
  645. ;;;
  646. ;;; I use the dreaded call/cc to do local aborts. A good compiler could
  647. ;;; handle this with extreme efficiency. An implementation that provides
  648. ;;; a one-shot, non-persistent continuation grabber could help the compiler
  649. ;;; out by using that in place of the call/cc's in these routines.
  650. ;;;
  651. ;;; These functions have funky definitions that are precisely tuned to
  652. ;;; the needs of the fold/map procs -- for example, to minimize the number
  653. ;;; of times the argument lists need to be examined.
  654. ;;; Return (map cdr lists).
  655. ;;; However, if any element of LISTS is empty, just abort and return '().
  656. (define (%cdrs lists)
  657. (call-with-current-continuation
  658. (lambda (abort)
  659. (let recur ((lists lists))
  660. (if (pair? lists)
  661. (let ((lis (car lists)))
  662. (if (null-list? lis) (abort '())
  663. (cons (cdr lis) (recur (cdr lists)))))
  664. '())))))
  665. (define (%cars+ lists last-elt) ; (append! (map car lists) (list last-elt))
  666. (let recur ((lists lists))
  667. (if (pair? lists) (cons (caar lists) (recur (cdr lists))) (list last-elt))))
  668. ;;; LISTS is a (not very long) non-empty list of lists.
  669. ;;; Return two lists: the cars & the cdrs of the lists.
  670. ;;; However, if any of the lists is empty, just abort and return [() ()].
  671. (define (%cars+cdrs lists)
  672. (call-with-current-continuation
  673. (lambda (abort)
  674. (let recur ((lists lists))
  675. (if (pair? lists)
  676. (receive (list other-lists) (car+cdr lists)
  677. (if (null-list? list) (abort '() '()) ; LIST is empty -- bail out
  678. (receive (a d) (car+cdr list)
  679. (receive (cars cdrs) (recur other-lists)
  680. (values (cons a cars) (cons d cdrs))))))
  681. (values '() '()))))))
  682. ;;; Like %CARS+CDRS, but we pass in a final elt tacked onto the end of the
  683. ;;; cars list. What a hack.
  684. (define (%cars+cdrs+ lists cars-final)
  685. (call-with-current-continuation
  686. (lambda (abort)
  687. (let recur ((lists lists))
  688. (if (pair? lists)
  689. (receive (list other-lists) (car+cdr lists)
  690. (if (null-list? list) (abort '() '()) ; LIST is empty -- bail out
  691. (receive (a d) (car+cdr list)
  692. (receive (cars cdrs) (recur other-lists)
  693. (values (cons a cars) (cons d cdrs))))))
  694. (values (list cars-final) '()))))))
  695. ;;; Like %CARS+CDRS, but blow up if any list is empty.
  696. (define (%cars+cdrs/no-test lists)
  697. (let recur ((lists lists))
  698. (if (pair? lists)
  699. (receive (list other-lists) (car+cdr lists)
  700. (receive (a d) (car+cdr list)
  701. (receive (cars cdrs) (recur other-lists)
  702. (values (cons a cars) (cons d cdrs)))))
  703. (values '() '()))))
  704. ;;; count
  705. ;;;;;;;;;
  706. (define (count pred list1 . lists)
  707. (check-arg procedure? pred count)
  708. (if (pair? lists)
  709. ;; N-ary case
  710. (let lp ((list1 list1) (lists lists) (i 0))
  711. (if (null-list? list1) i
  712. (receive (as ds) (%cars+cdrs lists)
  713. (if (null? as) i
  714. (lp (cdr list1) ds
  715. (if (apply pred (car list1) as) (+ i 1) i))))))
  716. ;; Fast path
  717. (let lp ((lis list1) (i 0))
  718. (if (null-list? lis) i
  719. (lp (cdr lis) (if (pred (car lis)) (+ i 1) i))))))
  720. ;;; fold/unfold
  721. ;;;;;;;;;;;;;;;
  722. (define (unfold-right p f g seed . maybe-tail)
  723. (check-arg procedure? p unfold-right)
  724. (check-arg procedure? f unfold-right)
  725. (check-arg procedure? g unfold-right)
  726. (let lp ((seed seed) (ans (:optional maybe-tail '())))
  727. (if (p seed) ans
  728. (lp (g seed)
  729. (cons (f seed) ans)))))
  730. (define (unfold p f g seed . maybe-tail-gen)
  731. (check-arg procedure? p unfold)
  732. (check-arg procedure? f unfold)
  733. (check-arg procedure? g unfold)
  734. (if (pair? maybe-tail-gen)
  735. (let ((tail-gen (car maybe-tail-gen)))
  736. (if (pair? (cdr maybe-tail-gen))
  737. (apply error "Too many arguments" unfold p f g seed maybe-tail-gen)
  738. (let recur ((seed seed))
  739. (if (p seed) (tail-gen seed)
  740. (cons (f seed) (recur (g seed)))))))
  741. (let recur ((seed seed))
  742. (if (p seed) '()
  743. (cons (f seed) (recur (g seed)))))))
  744. (define (fold kons knil lis1 . lists)
  745. (check-arg procedure? kons fold)
  746. (if (pair? lists)
  747. (let lp ((lists (cons lis1 lists)) (ans knil)) ; N-ary case
  748. (receive (cars+ans cdrs) (%cars+cdrs+ lists ans)
  749. (if (null? cars+ans) ans ; Done.
  750. (lp cdrs (apply kons cars+ans)))))
  751. (let lp ((lis lis1) (ans knil)) ; Fast path
  752. (if (null-list? lis) ans
  753. (lp (cdr lis) (kons (car lis) ans))))))
  754. (define (fold-right kons knil lis1 . lists)
  755. (check-arg procedure? kons fold-right)
  756. (if (pair? lists)
  757. (let recur ((lists (cons lis1 lists))) ; N-ary case
  758. (let ((cdrs (%cdrs lists)))
  759. (if (null? cdrs) knil
  760. (apply kons (%cars+ lists (recur cdrs))))))
  761. (let recur ((lis lis1)) ; Fast path
  762. (if (null-list? lis) knil
  763. (let ((head (car lis)))
  764. (kons head (recur (cdr lis))))))))
  765. (define (pair-fold-right f zero lis1 . lists)
  766. (check-arg procedure? f pair-fold-right)
  767. (if (pair? lists)
  768. (let recur ((lists (cons lis1 lists))) ; N-ary case
  769. (let ((cdrs (%cdrs lists)))
  770. (if (null? cdrs) zero
  771. (apply f (append! lists (list (recur cdrs)))))))
  772. (let recur ((lis lis1)) ; Fast path
  773. (if (null-list? lis) zero (f lis (recur (cdr lis)))))))
  774. (define (pair-fold f zero lis1 . lists)
  775. (check-arg procedure? f pair-fold)
  776. (if (pair? lists)
  777. (let lp ((lists (cons lis1 lists)) (ans zero)) ; N-ary case
  778. (let ((tails (%cdrs lists)))
  779. (if (null? tails) ans
  780. (lp tails (apply f (append! lists (list ans)))))))
  781. (let lp ((lis lis1) (ans zero))
  782. (if (null-list? lis) ans
  783. (let ((tail (cdr lis))) ; Grab the cdr now,
  784. (lp tail (f lis ans))))))) ; in case F SET-CDR!s LIS.
  785. ;;; REDUCE and REDUCE-RIGHT only use RIDENTITY in the empty-list case.
  786. ;;; These cannot meaningfully be n-ary.
  787. (define (reduce f ridentity lis)
  788. (check-arg procedure? f reduce)
  789. (if (null-list? lis) ridentity
  790. (fold f (car lis) (cdr lis))))
  791. (define (reduce-right f ridentity lis)
  792. (check-arg procedure? f reduce-right)
  793. (if (null-list? lis) ridentity
  794. (let recur ((head (car lis)) (lis (cdr lis)))
  795. (if (pair? lis)
  796. (f head (recur (car lis) (cdr lis)))
  797. head))))
  798. ;;; Mappers: append-map append-map! pair-for-each map! filter-map map-in-order
  799. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  800. (define (append-map f lis1 . lists)
  801. (really-append-map append-map append f lis1 lists))
  802. (define (append-map! f lis1 . lists)
  803. (really-append-map append-map! append! f lis1 lists))
  804. (define (really-append-map who appender f lis1 lists)
  805. (check-arg procedure? f who)
  806. (if (pair? lists)
  807. (receive (cars cdrs) (%cars+cdrs (cons lis1 lists))
  808. (if (null? cars) '()
  809. (let recur ((cars cars) (cdrs cdrs))
  810. (let ((vals (apply f cars)))
  811. (receive (cars2 cdrs2) (%cars+cdrs cdrs)
  812. (if (null? cars2) vals
  813. (appender vals (recur cars2 cdrs2))))))))
  814. ;; Fast path
  815. (if (null-list? lis1) '()
  816. (let recur ((elt (car lis1)) (rest (cdr lis1)))
  817. (let ((vals (f elt)))
  818. (if (null-list? rest) vals
  819. (appender vals (recur (car rest) (cdr rest)))))))))
  820. (define (pair-for-each proc lis1 . lists)
  821. (check-arg procedure? proc pair-for-each)
  822. (if (pair? lists)
  823. (let lp ((lists (cons lis1 lists)))
  824. (let ((tails (%cdrs lists)))
  825. (if (pair? tails)
  826. (begin (apply proc lists)
  827. (lp tails)))))
  828. ;; Fast path.
  829. (let lp ((lis lis1))
  830. (if (not (null-list? lis))
  831. (let ((tail (cdr lis))) ; Grab the cdr now,
  832. (proc lis) ; in case PROC SET-CDR!s LIS.
  833. (lp tail))))))
  834. ;;; We stop when LIS1 runs out, not when any list runs out.
  835. (define (map! f lis1 . lists)
  836. (check-arg procedure? f map!)
  837. (if (pair? lists)
  838. (let lp ((lis1 lis1) (lists lists))
  839. (if (not (null-list? lis1))
  840. (receive (heads tails) (%cars+cdrs/no-test lists)
  841. (set-car! lis1 (apply f (car lis1) heads))
  842. (lp (cdr lis1) tails))))
  843. ;; Fast path.
  844. (pair-for-each (lambda (pair) (set-car! pair (f (car pair)))) lis1))
  845. lis1)
  846. ;;; Map F across L, and save up all the non-false results.
  847. (define (filter-map f lis1 . lists)
  848. (check-arg procedure? f filter-map)
  849. (if (pair? lists)
  850. (let recur ((lists (cons lis1 lists)))
  851. (receive (cars cdrs) (%cars+cdrs lists)
  852. (if (pair? cars)
  853. (cond ((apply f cars) => (lambda (x) (cons x (recur cdrs))))
  854. (else (recur cdrs))) ; Tail call in this arm.
  855. '())))
  856. ;; Fast path.
  857. (let recur ((lis lis1))
  858. (if (null-list? lis) lis
  859. (let ((tail (recur (cdr lis))))
  860. (cond ((f (car lis)) => (lambda (x) (cons x tail)))
  861. (else tail)))))))
  862. ;;; Map F across lists, guaranteeing to go left-to-right.
  863. ;;; NOTE: Some implementations of R5RS MAP are compliant with this spec;
  864. ;;; in which case this procedure may simply be defined as a synonym for MAP.
  865. (define (map-in-order f lis1 . lists)
  866. (check-arg procedure? f map-in-order)
  867. (if (pair? lists)
  868. (let recur ((lists (cons lis1 lists)))
  869. (receive (cars cdrs) (%cars+cdrs lists)
  870. (if (pair? cars)
  871. (let ((x (apply f cars))) ; Do head first,
  872. (cons x (recur cdrs))) ; then tail.
  873. '())))
  874. ;; Fast path.
  875. (let recur ((lis lis1))
  876. (if (null-list? lis) lis
  877. (let ((tail (cdr lis))
  878. (x (f (car lis)))) ; Do head first,
  879. (cons x (recur tail))))))) ; then tail.
  880. ;;; We extend MAP to handle arguments of unequal length.
  881. (define map map-in-order)
  882. ;;; Apply F across lists, guaranteeing to go left-to-right.
  883. ;;; NOTE: Some implementations of R5RS MAP are compliant with this spec;
  884. ;;; in which case this procedure may simply be defined as a synonym for FOR-EACH.
  885. (define (for-each f lis1 . lists)
  886. (check-arg procedure? f for-each)
  887. (if (pair? lists)
  888. (let recur ((lists (cons lis1 lists)))
  889. (receive (cars cdrs) (%cars+cdrs lists)
  890. (if (pair? cars)
  891. (begin
  892. (apply f cars) ; Do head first,
  893. (recur cdrs))))) ; then tail.
  894. ;; Fast path.
  895. (let recur ((lis lis1))
  896. (if (not (null-list? lis))
  897. (begin
  898. (f (car lis)) ; Do head first,
  899. (recur (cdr lis))))))) ; then tail.
  900. ;;; filter, remove, partition
  901. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  902. ;;; FILTER, REMOVE, PARTITION and their destructive counterparts do not
  903. ;;; disorder the elements of their argument.
  904. ;; This FILTER shares the longest tail of L that has no deleted elements.
  905. ;; If Scheme had multi-continuation calls, they could be made more efficient.
  906. (define (filter pred lis) ; Sleazing with EQ? makes this
  907. (check-arg procedure? pred filter) ; one faster.
  908. (let recur ((lis lis))
  909. (if (null-list? lis) lis ; Use NOT-PAIR? to handle dotted lists.
  910. (let ((head (car lis))
  911. (tail (cdr lis)))
  912. (if (pred head)
  913. (let ((new-tail (recur tail))) ; Replicate the RECUR call so
  914. (if (eq? tail new-tail) lis
  915. (cons head new-tail)))
  916. (recur tail)))))) ; this one can be a tail call.
  917. ;;; Another version that shares longest tail.
  918. ;(define (filter pred lis)
  919. ; (receive (ans no-del?)
  920. ; ;; (recur l) returns L with (pred x) values filtered.
  921. ; ;; It also returns a flag NO-DEL? if the returned value
  922. ; ;; is EQ? to L, i.e. if it didn't have to delete anything.
  923. ; (let recur ((l l))
  924. ; (if (null-list? l) (values l #t)
  925. ; (let ((x (car l))
  926. ; (tl (cdr l)))
  927. ; (if (pred x)
  928. ; (receive (ans no-del?) (recur tl)
  929. ; (if no-del?
  930. ; (values l #t)
  931. ; (values (cons x ans) #f)))
  932. ; (receive (ans no-del?) (recur tl) ; Delete X.
  933. ; (values ans #f))))))
  934. ; ans))
  935. ;(define (filter! pred lis) ; Things are much simpler
  936. ; (let recur ((lis lis)) ; if you are willing to
  937. ; (if (pair? lis) ; push N stack frames & do N
  938. ; (cond ((pred (car lis)) ; SET-CDR! writes, where N is
  939. ; (set-cdr! lis (recur (cdr lis))); the length of the answer.
  940. ; lis)
  941. ; (else (recur (cdr lis))))
  942. ; lis)))
  943. ;;; This implementation of FILTER!
  944. ;;; - doesn't cons, and uses no stack;
  945. ;;; - is careful not to do redundant SET-CDR! writes, as writes to memory are
  946. ;;; usually expensive on modern machines, and can be extremely expensive on
  947. ;;; modern Schemes (e.g., ones that have generational GC's).
  948. ;;; It just zips down contiguous runs of in and out elts in LIS doing the
  949. ;;; minimal number of SET-CDR!s to splice the tail of one run of ins to the
  950. ;;; beginning of the next.
  951. (define (filter! pred lis)
  952. (check-arg procedure? pred filter!)
  953. (let lp ((ans lis))
  954. (cond ((null-list? ans) ans) ; Scan looking for
  955. ((not (pred (car ans))) (lp (cdr ans))) ; first cons of result.
  956. ;; ANS is the eventual answer.
  957. ;; SCAN-IN: (CDR PREV) = LIS and (CAR PREV) satisfies PRED.
  958. ;; Scan over a contiguous segment of the list that
  959. ;; satisfies PRED.
  960. ;; SCAN-OUT: (CAR PREV) satisfies PRED. Scan over a contiguous
  961. ;; segment of the list that *doesn't* satisfy PRED.
  962. ;; When the segment ends, patch in a link from PREV
  963. ;; to the start of the next good segment, and jump to
  964. ;; SCAN-IN.
  965. (else (letrec ((scan-in (lambda (prev lis)
  966. (if (pair? lis)
  967. (if (pred (car lis))
  968. (scan-in lis (cdr lis))
  969. (scan-out prev (cdr lis))))))
  970. (scan-out (lambda (prev lis)
  971. (let lp ((lis lis))
  972. (if (pair? lis)
  973. (if (pred (car lis))
  974. (begin (set-cdr! prev lis)
  975. (scan-in lis (cdr lis)))
  976. (lp (cdr lis)))
  977. (set-cdr! prev lis))))))
  978. (scan-in ans (cdr ans))
  979. ans)))))
  980. ;;; Answers share common tail with LIS where possible;
  981. ;;; the technique is slightly subtle.
  982. (define (partition pred lis)
  983. (check-arg procedure? pred partition)
  984. (let recur ((lis lis))
  985. (if (null-list? lis) (values lis lis) ; Use NOT-PAIR? to handle dotted lists.
  986. (let ((elt (car lis))
  987. (tail (cdr lis)))
  988. (receive (in out) (recur tail)
  989. (if (pred elt)
  990. (values (if (pair? out) (cons elt in) lis) out)
  991. (values in (if (pair? in) (cons elt out) lis))))))))
  992. ;(define (partition! pred lis) ; Things are much simpler
  993. ; (let recur ((lis lis)) ; if you are willing to
  994. ; (if (null-list? lis) (values lis lis) ; push N stack frames & do N
  995. ; (let ((elt (car lis))) ; SET-CDR! writes, where N is
  996. ; (receive (in out) (recur (cdr lis)) ; the length of LIS.
  997. ; (cond ((pred elt)
  998. ; (set-cdr! lis in)
  999. ; (values lis out))
  1000. ; (else (set-cdr! lis out)
  1001. ; (values in lis))))))))
  1002. ;;; This implementation of PARTITION!
  1003. ;;; - doesn't cons, and uses no stack;
  1004. ;;; - is careful not to do redundant SET-CDR! writes, as writes to memory are
  1005. ;;; usually expensive on modern machines, and can be extremely expensive on
  1006. ;;; modern Schemes (e.g., ones that have generational GC's).
  1007. ;;; It just zips down contiguous runs of in and out elts in LIS doing the
  1008. ;;; minimal number of SET-CDR!s to splice these runs together into the result
  1009. ;;; lists.
  1010. (define (partition! pred lis)
  1011. (check-arg procedure? pred partition!)
  1012. (if (null-list? lis) (values lis lis)
  1013. ;; This pair of loops zips down contiguous in & out runs of the
  1014. ;; list, splicing the runs together. The invariants are
  1015. ;; SCAN-IN: (cdr in-prev) = LIS.
  1016. ;; SCAN-OUT: (cdr out-prev) = LIS.
  1017. (letrec ((scan-in (lambda (in-prev out-prev lis)
  1018. (let lp ((in-prev in-prev) (lis lis))
  1019. (if (pair? lis)
  1020. (if (pred (car lis))
  1021. (lp lis (cdr lis))
  1022. (begin (set-cdr! out-prev lis)
  1023. (scan-out in-prev lis (cdr lis))))
  1024. (set-cdr! out-prev lis))))) ; Done.
  1025. (scan-out (lambda (in-prev out-prev lis)
  1026. (let lp ((out-prev out-prev) (lis lis))
  1027. (if (pair? lis)
  1028. (if (pred (car lis))
  1029. (begin (set-cdr! in-prev lis)
  1030. (scan-in lis out-prev (cdr lis)))
  1031. (lp lis (cdr lis)))
  1032. (set-cdr! in-prev lis)))))) ; Done.
  1033. ;; Crank up the scan&splice loops.
  1034. (if (pred (car lis))
  1035. ;; LIS begins in-list. Search for out-list's first pair.
  1036. (let lp ((prev-l lis) (l (cdr lis)))
  1037. (cond ((not (pair? l)) (values lis l))
  1038. ((pred (car l)) (lp l (cdr l)))
  1039. (else (scan-out prev-l l (cdr l))
  1040. (values lis l)))) ; Done.
  1041. ;; LIS begins out-list. Search for in-list's first pair.
  1042. (let lp ((prev-l lis) (l (cdr lis)))
  1043. (cond ((not (pair? l)) (values l lis))
  1044. ((pred (car l))
  1045. (scan-in l prev-l (cdr l))
  1046. (values l lis)) ; Done.
  1047. (else (lp l (cdr l)))))))))
  1048. ;;; Inline us, please.
  1049. (define (remove pred l) (filter (lambda (x) (not (pred x))) l))
  1050. (define (remove! pred l) (filter! (lambda (x) (not (pred x))) l))
  1051. ;;; Here's the taxonomy for the DELETE/ASSOC/MEMBER functions.
  1052. ;;; (I don't actually think these are the world's most important
  1053. ;;; functions -- the procedural FILTER/REMOVE/FIND/FIND-TAIL variants
  1054. ;;; are far more general.)
  1055. ;;;
  1056. ;;; Function Action
  1057. ;;; ---------------------------------------------------------------------------
  1058. ;;; remove pred lis Delete by general predicate
  1059. ;;; delete x lis [=] Delete by element comparison
  1060. ;;;
  1061. ;;; find pred lis Search by general predicate
  1062. ;;; find-tail pred lis Search by general predicate
  1063. ;;; member x lis [=] Search by element comparison
  1064. ;;;
  1065. ;;; assoc key lis [=] Search alist by key comparison
  1066. ;;; alist-delete key alist [=] Alist-delete by key comparison
  1067. (define (delete x lis . maybe-=)
  1068. (let ((= (:optional maybe-= equal?)))
  1069. (filter (lambda (y) (not (= x y))) lis)))
  1070. (define (delete! x lis . maybe-=)
  1071. (let ((= (:optional maybe-= equal?)))
  1072. (filter! (lambda (y) (not (= x y))) lis)))
  1073. ;;; Extended from R4RS to take an optional comparison argument.
  1074. (define (member x lis . maybe-=)
  1075. (let ((= (:optional maybe-= equal?)))
  1076. (find-tail (lambda (y) (= x y)) lis)))
  1077. ;;; R4RS, hence we don't bother to define.
  1078. ;;; The MEMBER and then FIND-TAIL call should definitely
  1079. ;;; be inlined for MEMQ & MEMV.
  1080. ;(define (memq x lis) (member x lis eq?))
  1081. ;(define (memv x lis) (member x lis eqv?))
  1082. ;;; right-duplicate deletion
  1083. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  1084. ;;; delete-duplicates delete-duplicates!
  1085. ;;;
  1086. ;;; Beware -- these are N^2 algorithms. To efficiently remove duplicates
  1087. ;;; in long lists, sort the list to bring duplicates together, then use a
  1088. ;;; linear-time algorithm to kill the dups. Or use an algorithm based on
  1089. ;;; element-marking. The former gives you O(n lg n), the latter is linear.
  1090. (define (delete-duplicates lis . maybe-=)
  1091. (let ((elt= (:optional maybe-= equal?)))
  1092. (check-arg procedure? elt= delete-duplicates)
  1093. (let recur ((lis lis))
  1094. (if (null-list? lis) lis
  1095. (let* ((x (car lis))
  1096. (tail (cdr lis))
  1097. (new-tail (recur (delete x tail elt=))))
  1098. (if (eq? tail new-tail) lis (cons x new-tail)))))))
  1099. (define (delete-duplicates! lis . maybe-=)
  1100. (let ((elt= (:optional maybe-= equal?)))
  1101. (check-arg procedure? elt= delete-duplicates!)
  1102. (let recur ((lis lis))
  1103. (if (null-list? lis) lis
  1104. (let* ((x (car lis))
  1105. (tail (cdr lis))
  1106. (new-tail (recur (delete! x tail elt=))))
  1107. (if (eq? tail new-tail) lis (cons x new-tail)))))))
  1108. ;;; alist stuff
  1109. ;;;;;;;;;;;;;;;
  1110. ;;; Extended from R4RS to take an optional comparison argument.
  1111. (define (assoc x lis . maybe-=)
  1112. (let ((= (:optional maybe-= equal?)))
  1113. (find (lambda (entry) (= x (car entry))) lis)))
  1114. (define (alist-cons key datum alist) (cons (cons key datum) alist))
  1115. (define (alist-copy alist)
  1116. (map (lambda (elt) (cons (car elt) (cdr elt)))
  1117. alist))
  1118. (define (alist-delete key alist . maybe-=)
  1119. (let ((= (:optional maybe-= equal?)))
  1120. (filter (lambda (elt) (not (= key (car elt)))) alist)))
  1121. (define (alist-delete! key alist . maybe-=)
  1122. (let ((= (:optional maybe-= equal?)))
  1123. (filter! (lambda (elt) (not (= key (car elt)))) alist)))
  1124. ;;; find find-tail take-while drop-while span break any every list-index
  1125. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  1126. (define (find pred list)
  1127. (cond ((find-tail pred list) => car)
  1128. (else #f)))
  1129. (define (find-tail pred list)
  1130. (check-arg procedure? pred find-tail)
  1131. (let lp ((list list))
  1132. (and (not (null-list? list))
  1133. (if (pred (car list)) list
  1134. (lp (cdr list))))))
  1135. (define (take-while pred lis)
  1136. (check-arg procedure? pred take-while)
  1137. (let recur ((lis lis))
  1138. (if (null-list? lis) '()
  1139. (let ((x (car lis)))
  1140. (if (pred x)
  1141. (cons x (recur (cdr lis)))
  1142. '())))))
  1143. (define (drop-while pred lis)
  1144. (check-arg procedure? pred drop-while)
  1145. (let lp ((lis lis))
  1146. (if (null-list? lis) '()
  1147. (if (pred (car lis))
  1148. (lp (cdr lis))
  1149. lis))))
  1150. (define (take-while! pred lis)
  1151. (check-arg procedure? pred take-while!)
  1152. (if (or (null-list? lis) (not (pred (car lis)))) '()
  1153. (begin (let lp ((prev lis) (rest (cdr lis)))
  1154. (if (pair? rest)
  1155. (let ((x (car rest)))
  1156. (if (pred x) (lp rest (cdr rest))
  1157. (set-cdr! prev '())))))
  1158. lis)))
  1159. (define (span pred lis)
  1160. (check-arg procedure? pred span)
  1161. (let recur ((lis lis))
  1162. (if (null-list? lis) (values '() '())
  1163. (let ((x (car lis)))
  1164. (if (pred x)
  1165. (receive (prefix suffix) (recur (cdr lis))
  1166. (values (cons x prefix) suffix))
  1167. (values '() lis))))))
  1168. (define (span! pred lis)
  1169. (check-arg procedure? pred span!)
  1170. (if (or (null-list? lis) (not (pred (car lis)))) (values '() lis)
  1171. (let ((suffix (let lp ((prev lis) (rest (cdr lis)))
  1172. (if (null-list? rest) rest
  1173. (let ((x (car rest)))
  1174. (if (pred x) (lp rest (cdr rest))
  1175. (begin (set-cdr! prev '())
  1176. rest)))))))
  1177. (values lis suffix))))
  1178. (define (break pred lis) (span (lambda (x) (not (pred x))) lis))
  1179. (define (break! pred lis) (span! (lambda (x) (not (pred x))) lis))
  1180. (define (any pred lis1 . lists)
  1181. (check-arg procedure? pred any)
  1182. (if (pair? lists)
  1183. ;; N-ary case
  1184. (receive (heads tails) (%cars+cdrs (cons lis1 lists))
  1185. (and (pair? heads)
  1186. (let lp ((heads heads) (tails tails))
  1187. (receive (next-heads next-tails) (%cars+cdrs tails)
  1188. (if (pair? next-heads)
  1189. (or (apply pred heads) (lp next-heads next-tails))
  1190. (apply pred heads)))))) ; Last PRED app is tail call.
  1191. ;; Fast path
  1192. (and (not (null-list? lis1))
  1193. (let lp ((head (car lis1)) (tail (cdr lis1)))
  1194. (if (null-list? tail)
  1195. (pred head) ; Last PRED app is tail call.
  1196. (or (pred head) (lp (car tail) (cdr tail))))))))
  1197. ;(define (every pred list) ; Simple definition.
  1198. ; (let lp ((list list)) ; Doesn't return the last PRED value.
  1199. ; (or (not (pair? list))
  1200. ; (and (pred (car list))
  1201. ; (lp (cdr list))))))
  1202. (define (every pred lis1 . lists)
  1203. (check-arg procedure? pred every)
  1204. (if (pair? lists)
  1205. ;; N-ary case
  1206. (receive (heads tails) (%cars+cdrs (cons lis1 lists))
  1207. (or (not (pair? heads))
  1208. (let lp ((heads heads) (tails tails))
  1209. (receive (next-heads next-tails) (%cars+cdrs tails)
  1210. (if (pair? next-heads)
  1211. (and (apply pred heads) (lp next-heads next-tails))
  1212. (apply pred heads)))))) ; Last PRED app is tail call.
  1213. ;; Fast path
  1214. (or (null-list? lis1)
  1215. (let lp ((head (car lis1)) (tail (cdr lis1)))
  1216. (if (null-list? tail)
  1217. (pred head) ; Last PRED app is tail call.
  1218. (and (pred head) (lp (car tail) (cdr tail))))))))
  1219. (define (list-index pred lis1 . lists)
  1220. (check-arg procedure? pred list-index)
  1221. (if (pair? lists)
  1222. ;; N-ary case
  1223. (let lp ((lists (cons lis1 lists)) (n 0))
  1224. (receive (heads tails) (%cars+cdrs lists)
  1225. (and (pair? heads)
  1226. (if (apply pred heads) n
  1227. (lp tails (+ n 1))))))
  1228. ;; Fast path
  1229. (let lp ((lis lis1) (n 0))
  1230. (and (not (null-list? lis))
  1231. (if (pred (car lis)) n (lp (cdr lis) (+ n 1)))))))
  1232. ;;; Reverse
  1233. ;;;;;;;;;;;
  1234. ;R4RS, so not defined here.
  1235. ;(define (reverse lis) (fold cons '() lis))
  1236. ;(define (reverse! lis)
  1237. ; (pair-fold (lambda (pair tail) (set-cdr! pair tail) pair) '() lis))
  1238. (define (reverse! lis)
  1239. (let lp ((lis lis) (ans '()))
  1240. (if (null-list? lis) ans
  1241. (let ((tail (cdr lis)))
  1242. (set-cdr! lis ans)
  1243. (lp tail lis)))))
  1244. ;;; Lists-as-sets
  1245. ;;;;;;;;;;;;;;;;;
  1246. ;;; This is carefully tuned code; do not modify casually.
  1247. ;;; - It is careful to share storage when possible;
  1248. ;;; - Side-effecting code tries not to perform redundant writes.
  1249. ;;; - It tries to avoid linear-time scans in special cases where constant-time
  1250. ;;; computations can be performed.
  1251. ;;; - It relies on similar properties from the other list-lib procs it calls.
  1252. ;;; For example, it uses the fact that the implementations of MEMBER and
  1253. ;;; FILTER in this source code share longest common tails between args
  1254. ;;; and results to get structure sharing in the lset procedures.
  1255. (define (%lset2<= = lis1 lis2) (every (lambda (x) (member x lis2 =)) lis1))
  1256. (define (lset<= = . lists)
  1257. (check-arg procedure? = lset<=)
  1258. (or (not (pair? lists)) ; 0-ary case
  1259. (let lp ((s1 (car lists)) (rest (cdr lists)))
  1260. (or (not (pair? rest))
  1261. (let ((s2 (car rest)) (rest (cdr rest)))
  1262. (and (or (eq? s2 s1) ; Fast path
  1263. (%lset2<= = s1 s2)) ; Real test
  1264. (lp s2 rest)))))))
  1265. (define (lset= = . lists)
  1266. (check-arg procedure? = lset=)
  1267. (or (not (pair? lists)) ; 0-ary case
  1268. (let lp ((s1 (car lists)) (rest (cdr lists)))
  1269. (or (not (pair? rest))
  1270. (let ((s2 (car rest))
  1271. (rest (cdr rest)))
  1272. (and (or (eq? s1 s2) ; Fast path
  1273. (and (%lset2<= = s1 s2) (%lset2<= = s2 s1))) ; Real test
  1274. (lp s2 rest)))))))
  1275. (define (lset-adjoin = lis . elts)
  1276. (check-arg procedure? = lset-adjoin)
  1277. (fold (lambda (elt ans) (if (member elt ans =) ans (cons elt ans)))
  1278. lis elts))
  1279. (define (lset-union = . lists)
  1280. (check-arg procedure? = lset-union)
  1281. (reduce (lambda (lis ans) ; Compute ANS + LIS.
  1282. (cond ((null? lis) ans) ; Don't copy any lists
  1283. ((null? ans) lis) ; if we don't have to.
  1284. ((eq? lis ans) ans)
  1285. (else
  1286. (fold (lambda (elt ans) (if (any (lambda (x) (= x elt)) ans)
  1287. ans
  1288. (cons elt ans)))
  1289. ans lis))))
  1290. '() lists))
  1291. (define (lset-union! = . lists)
  1292. (check-arg procedure? = lset-union!)
  1293. (reduce (lambda (lis ans) ; Splice new elts of LIS onto the front of ANS.
  1294. (cond ((null? lis) ans) ; Don't copy any lists
  1295. ((null? ans) lis) ; if we don't have to.
  1296. ((eq? lis ans) ans)
  1297. (else
  1298. (pair-fold (lambda (pair ans)
  1299. (let ((elt (car pair)))
  1300. (if (any (lambda (x) (= x elt)) ans)
  1301. ans
  1302. (begin (set-cdr! pair ans) pair))))
  1303. ans lis))))
  1304. '() lists))
  1305. (define (lset-intersection = lis1 . lists)
  1306. (check-arg procedure? = lset-intersection)
  1307. (let ((lists (delete lis1 lists eq?))) ; Throw out any LIS1 vals.
  1308. (cond ((any null-list? lists) '()) ; Short cut
  1309. ((null? lists) lis1) ; Short cut
  1310. (else (filter (lambda (x)
  1311. (every (lambda (lis) (member x lis =)) lists))
  1312. lis1)))))
  1313. (define (lset-intersection! = lis1 . lists)
  1314. (check-arg procedure? = lset-intersection!)
  1315. (let ((lists (delete lis1 lists eq?))) ; Throw out any LIS1 vals.
  1316. (cond ((any null-list? lists) '()) ; Short cut
  1317. ((null? lists) lis1) ; Short cut
  1318. (else (filter! (lambda (x)
  1319. (every (lambda (lis) (member x lis =)) lists))
  1320. lis1)))))
  1321. (define (lset-difference = lis1 . lists)
  1322. (check-arg procedure? = lset-difference)
  1323. (let ((lists (filter pair? lists))) ; Throw out empty lists.
  1324. (cond ((null? lists) lis1) ; Short cut
  1325. ((memq lis1 lists) '()) ; Short cut
  1326. (else (filter (lambda (x)
  1327. (every (lambda (lis) (not (member x lis =)))
  1328. lists))
  1329. lis1)))))
  1330. (define (lset-difference! = lis1 . lists)
  1331. (check-arg procedure? = lset-difference!)
  1332. (let ((lists (filter pair? lists))) ; Throw out empty lists.
  1333. (cond ((null? lists) lis1) ; Short cut
  1334. ((memq lis1 lists) '()) ; Short cut
  1335. (else (filter! (lambda (x)
  1336. (every (lambda (lis) (not (member x lis =)))
  1337. lists))
  1338. lis1)))))
  1339. (define (lset-xor = . lists)
  1340. (check-arg procedure? = lset-xor)
  1341. (reduce (lambda (b a) ; Compute A xor B:
  1342. ;; Note that this code relies on the constant-time
  1343. ;; short-cuts provided by LSET-DIFF+INTERSECTION,
  1344. ;; LSET-DIFFERENCE & APPEND to provide constant-time short
  1345. ;; cuts for the cases A = (), B = (), and A eq? B. It takes
  1346. ;; a careful case analysis to see it, but it's carefully
  1347. ;; built in.
  1348. ;; Compute a-b and a^b, then compute b-(a^b) and
  1349. ;; cons it onto the front of a-b.
  1350. (receive (a-b a-int-b) (lset-diff+intersection = a b)
  1351. (cond ((null? a-b) (lset-difference = b a))
  1352. ((null? a-int-b) (append b a))
  1353. (else (fold (lambda (xb ans)
  1354. (if (member xb a-int-b =) ans (cons xb ans)))
  1355. a-b
  1356. b)))))
  1357. '() lists))
  1358. (define (lset-xor! = . lists)
  1359. (check-arg procedure? = lset-xor!)
  1360. (reduce (lambda (b a) ; Compute A xor B:
  1361. ;; Note that this code relies on the constant-time
  1362. ;; short-cuts provided by LSET-DIFF+INTERSECTION,
  1363. ;; LSET-DIFFERENCE & APPEND to provide constant-time short
  1364. ;; cuts for the cases A = (), B = (), and A eq? B. It takes
  1365. ;; a careful case analysis to see it, but it's carefully
  1366. ;; built in.
  1367. ;; Compute a-b and a^b, then compute b-(a^b) and
  1368. ;; cons it onto the front of a-b.
  1369. (receive (a-b a-int-b) (lset-diff+intersection! = a b)
  1370. (cond ((null? a-b) (lset-difference! = b a))
  1371. ((null? a-int-b) (append! b a))
  1372. (else (pair-fold (lambda (b-pair ans)
  1373. (if (member (car b-pair) a-int-b =) ans
  1374. (begin (set-cdr! b-pair ans) b-pair)))
  1375. a-b
  1376. b)))))
  1377. '() lists))
  1378. (define (lset-diff+intersection = lis1 . lists)
  1379. (check-arg procedure? = lset-diff+intersection)
  1380. (cond ((every null-list? lists) (values lis1 '())) ; Short cut
  1381. ((memq lis1 lists) (values '() lis1)) ; Short cut
  1382. (else (partition (lambda (elt)
  1383. (not (any (lambda (lis) (member elt lis =))
  1384. lists)))
  1385. lis1))))
  1386. (define (lset-diff+intersection! = lis1 . lists)
  1387. (check-arg procedure? = lset-diff+intersection!)
  1388. (cond ((every null-list? lists) (values lis1 '())) ; Short cut
  1389. ((memq lis1 lists) (values '() lis1)) ; Short cut
  1390. (else (partition! (lambda (elt)
  1391. (not (any (lambda (lis) (member elt lis =))
  1392. lists)))
  1393. lis1))))