-
-
Notifications
You must be signed in to change notification settings - Fork 647
/
list.rkt
559 lines (515 loc) · 21.2 KB
/
list.rkt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
#lang racket/base
(provide first second third fourth fifth sixth seventh eighth ninth tenth
last-pair last rest
cons?
empty
empty?
make-list
drop
take
split-at
takef
dropf
splitf-at
drop-right
take-right
split-at-right
takef-right
dropf-right
splitf-at-right
append*
flatten
add-between
remove-duplicates
filter-map
count
partition
;; convenience
range
append-map
filter-not
shuffle
permutations
in-permutations
argmin
argmax)
(define (first x)
(if (and (pair? x) (list? x))
(car x)
(raise-argument-error 'first "(and/c list? (not/c empty?))" x)))
(define-syntax define-lgetter
(syntax-rules ()
[(_ name npos)
(define (name l0)
(if (list? l0)
(let loop ([l l0] [pos npos])
(if (pair? l)
(if (eq? pos 1) (car l) (loop (cdr l) (sub1 pos)))
(raise-arguments-error 'name
"list contains too few elements"
"list" l0)))
(raise-argument-error 'name "list?" l0)))]))
(define-lgetter second 2)
(define-lgetter third 3)
(define-lgetter fourth 4)
(define-lgetter fifth 5)
(define-lgetter sixth 6)
(define-lgetter seventh 7)
(define-lgetter eighth 8)
(define-lgetter ninth 9)
(define-lgetter tenth 10)
(define (last-pair l)
(if (pair? l)
(let loop ([l l] [x (cdr l)])
(if (pair? x)
(loop x (cdr x))
l))
(raise-argument-error 'last-pair "pair?" l)))
(define (last l)
(if (and (pair? l) (list? l))
(let loop ([l l] [x (cdr l)])
(if (pair? x)
(loop x (cdr x))
(car l)))
(raise-argument-error 'last "(and/c list? (not/c empty?))" l)))
(define (rest l)
(if (and (pair? l) (list? l))
(cdr l)
(raise-argument-error 'rest "(and/c list? (not/c empty?))" l)))
(define (cons? l) (pair? l))
(define (empty? l) (null? l))
(define empty '())
(define (make-list n x)
(unless (exact-nonnegative-integer? n)
(raise-argument-error 'make-list "exact-nonnegative-integer?" n))
(let loop ([n n] [r '()])
(if (zero? n) r (loop (sub1 n) (cons x r)))))
;; internal use below
(define (drop* list n) ; no error checking, returns #f if index is too large
(if (zero? n) list (and (pair? list) (drop* (cdr list) (sub1 n)))))
(define (too-large who list n)
(raise-arguments-error
who
(if (list? list)
"index is too large for list"
"index reaches a non-pair")
"index" n
(if (list? list)
"list"
"in")
list))
(define (take list0 n0)
(unless (exact-nonnegative-integer? n0)
(raise-argument-error 'take "exact-nonnegative-integer?" 1 list0 n0))
(let loop ([list list0] [n n0])
(cond [(zero? n) '()]
[(pair? list) (cons (car list) (loop (cdr list) (sub1 n)))]
[else (too-large 'take list0 n0)])))
(define (drop list n)
;; could be defined as `list-tail', but this is better for errors anyway
(unless (exact-nonnegative-integer? n)
(raise-argument-error 'drop "exact-nonnegative-integer?" 1 list n))
(or (drop* list n) (too-large 'drop list n)))
(define (split-at list0 n0)
(unless (exact-nonnegative-integer? n0)
(raise-argument-error 'split-at "exact-nonnegative-integer?" 1 list0 n0))
(let loop ([list list0] [n n0] [pfx '()])
(cond [(zero? n) (values (reverse pfx) list)]
[(pair? list) (loop (cdr list) (sub1 n) (cons (car list) pfx))]
[else (too-large 'split-at list0 n0)])))
(define (takef list pred)
(unless (procedure? pred)
(raise-argument-error 'takef "procedure?" 1 list pred))
(let loop ([list list])
(if (pair? list)
(let ([x (car list)])
(if (pred x)
(cons x (loop (cdr list)))
'()))
;; could return `list' here, but make it behave like `take'
;; exmaple: (takef '(a b c . d) symbol?) should be similar
;; to (take '(a b c . d) 3)
'())))
(define (dropf list pred)
(unless (procedure? pred)
(raise-argument-error 'dropf "procedure?" 1 list pred))
(let loop ([list list])
(if (and (pair? list) (pred (car list)))
(loop (cdr list))
list)))
(define (splitf-at list pred)
(unless (procedure? pred)
(raise-argument-error 'splitf-at "procedure?" 1 list pred))
(let loop ([list list] [pfx '()])
(if (and (pair? list) (pred (car list)))
(loop (cdr list) (cons (car list) pfx))
(values (reverse pfx) list))))
;; take/drop-right are originally from srfi-1, uses the same lead-pointer trick
(define (take-right list n)
(unless (exact-nonnegative-integer? n)
(raise-argument-error 'take-right "exact-nonnegative-integer?" 1 list n))
(let loop ([list list]
[lead (or (drop* list n) (too-large 'take-right list n))])
;; could throw an error for non-lists, but be more like `take'
(if (pair? lead)
(loop (cdr list) (cdr lead))
list)))
(define (drop-right list n)
(unless (exact-nonnegative-integer? n)
(raise-argument-error 'drop-right "exact-nonnegative-integer?" n))
(let loop ([list list]
[lead (or (drop* list n) (too-large 'drop-right list n))])
;; could throw an error for non-lists, but be more like `drop'
(if (pair? lead)
(cons (car list) (loop (cdr list) (cdr lead)))
'())))
(define (split-at-right list n)
(unless (exact-nonnegative-integer? n)
(raise-argument-error 'split-at-right "exact-nonnegative-integer?" n))
(let loop ([list list]
[lead (or (drop* list n) (too-large 'split-at-right list n))]
[pfx '()])
;; could throw an error for non-lists, but be more like `split-at'
(if (pair? lead)
(loop (cdr list) (cdr lead) (cons (car list) pfx))
(values (reverse pfx) list))))
;; For just `takef-right', it's possible to do something smart that
;; scans the list in order, keeping a pointer to the beginning of the
;; "current good block". This avoids a double scan *but* the payment is
;; in applying the predicate on all emlements. There might be a point
;; in that in some cases, but probably in most cases it's best to apply
;; it in reverse order, get the index, then do the usual thing -- in
;; many cases applying the predicate on all items could be more
;; expensive than the allocation needed for reverse.
;;
;; That's mildly useful in a completely unexciting way, but when it gets
;; to the other *f-right functions, it gets worse in that the first
;; approach won't work, so there's not much else to do than the second
;; one -- reverse the list, look for the place where the predicate flips
;; to #f, then use the non-f from-right functions above to do the work.
(define (count-from-right who list pred)
(unless (procedure? pred)
(raise-argument-error who "procedure?" 0 list pred))
(let loop ([list list] [rev '()] [n 0])
(if (pair? list)
(loop (cdr list) (cons (car list) rev) (add1 n))
(let loop ([n n] [list rev])
(if (and (pair? list) (pred (car list)))
(loop (sub1 n) (cdr list))
n)))))
(define (takef-right list pred)
(drop list (count-from-right 'takef-right list pred)))
(define (dropf-right list pred)
(take list (count-from-right 'dropf-right list pred)))
(define (splitf-at-right list pred)
(split-at list (count-from-right 'splitf-at-right list pred)))
(define append*
(case-lambda [(ls) (apply append ls)] ; optimize common case
[(l1 l2) (apply append l1 l2)]
[(l1 l2 l3) (apply append l1 l2 l3)]
[(l1 l2 l3 l4) (apply append l1 l2 l3 l4)]
[(l . lss) (apply apply append l lss)]))
(define (flatten orig-sexp)
(let loop ([sexp orig-sexp] [acc null])
(cond [(null? sexp) acc]
[(pair? sexp) (loop (car sexp) (loop (cdr sexp) acc))]
[else (cons sexp acc)])))
;; General note: many non-tail recursive, which are just as fast in racket
(define (add-between l x
#:splice? [splice? #f]
#:before-first [before-first '()]
#:before-last [before-last x]
#:after-last [after-last '()])
(unless (list? l)
(raise-argument-error 'add-between "list?" 0 l x))
(cond
[splice?
(define (check-list x which)
(unless (list? x)
(raise-arguments-error
'add-between
(string-append "list needed in splicing mode" which)
"given" x
"given list..." l)))
(check-list x "")
(check-list before-first " for #:before-first")
(check-list before-last " for #:before-last")
(check-list after-last " for #:after-last")]
[else
(define (check-not-given x which)
(unless (eq? '() x)
(raise-arguments-error
'add-between
(string-append which " can only be used in splicing mode")
"given" x
"given list..." l)))
(check-not-given before-first "#:before-first")
(check-not-given after-last "#:after-last")])
(cond
[(or (null? l) (null? (cdr l)))
(if splice? (append before-first l after-last) l)]
;; two cases for efficiency, maybe not needed
[splice?
(let* ([x (reverse x)]
;; main loop
[r (let loop ([i (cadr l)] [l (cddr l)] [r '()])
(if (pair? l)
(loop (car l) (cdr l) (cons i (append x r)))
(cons i (append (reverse before-last) r))))]
;; add `after-last' & reverse
[r (reverse (append (reverse after-last) r))]
;; add first item and `before-first'
[r `(,@before-first ,(car l) ,@r)])
r)]
[else
(cons (car l)
(reverse (let loop ([i (cadr l)] [l (cddr l)] [r '()]) ; main loop
(if (pair? l)
(loop (car l) (cdr l) (cons i (cons x r)))
(cons i (cons before-last r))))))]))
(define (remove-duplicates l [=? equal?] #:key [key #f])
;; `no-key' is used to optimize the case for long lists, it could be done for
;; shorter ones too, but that adds a ton of code to the result (about 2k).
(define-syntax-rule (no-key x) x)
(unless (list? l) (raise-argument-error 'remove-duplicates "list?" l))
(let* ([len (length l)]
[h (cond [(<= len 1) #t]
[(<= len 40) #f]
[(eq? =? eq?) (make-hasheq)]
[(eq? =? equal?) (make-hash)]
[else #f])])
(case h
[(#t) l]
[(#f)
;; plain n^2 list traversal (optimized for common cases) for short lists
;; and for equalities other than `eq?' or `equal?' The length threshold
;; above (40) was determined by trying it out with lists of length n
;; holding (random n) numbers.
(let ([key (or key (λ(x) x))])
(let-syntax ([loop (syntax-rules ()
[(_ search)
(let loop ([l l] [seen null])
(if (null? l)
l
(let* ([x (car l)] [k (key x)] [l (cdr l)])
(if (search k seen)
(loop l seen)
(cons x (loop l (cons k seen)))))))])])
(cond [(eq? =? equal?) (loop member)]
[(eq? =? eq?) (loop memq)]
[(eq? =? eqv?) (loop memv)]
[else (loop (λ(x seen) (ormap (λ(y) (=? x y)) seen)))])))]
[else
;; Use a hash for long lists with simple hash tables.
(let-syntax ([loop
(syntax-rules ()
[(_ getkey)
(let loop ([l l])
(if (null? l)
l
(let* ([x (car l)] [k (getkey x)] [l (cdr l)])
(if (hash-ref h k #f)
(loop l)
(begin (hash-set! h k #t)
(cons x (loop l)))))))])])
(if key (loop key) (loop no-key)))])))
(define (check-filter-arguments who f l ls)
(unless (procedure? f)
(raise-argument-error who "procedure?" f))
(unless (procedure-arity-includes? f (add1 (length ls)))
(raise-arguments-error
who "mismatch between procedure arity and argument count"
"procedure" f
"expected arity" (add1 (length ls))))
(unless (and (list? l) (andmap list? ls))
(for ([x (in-list (cons l ls))])
(unless (list? x) (raise-argument-error who "list?" x)))))
(define (filter-map f l . ls)
(check-filter-arguments 'filter-map f l ls)
(if (pair? ls)
(let ([len (length l)])
(if (andmap (λ(l) (= len (length l))) ls)
(let loop ([l l] [ls ls])
(if (null? l)
null
(let ([x (apply f (car l) (map car ls))])
(if x
(cons x (loop (cdr l) (map cdr ls)))
(loop (cdr l) (map cdr ls))))))
(raise-arguments-error 'filter-map "all lists must have same size")))
(let loop ([l l])
(if (null? l)
null
(let ([x (f (car l))])
(if x (cons x (loop (cdr l))) (loop (cdr l))))))))
;; very similar to `filter-map', one more such function will justify some macro
(define (count f l . ls)
(check-filter-arguments 'count f l ls)
(if (pair? ls)
(let ([len (length l)])
(if (andmap (λ(l) (= len (length l))) ls)
(let loop ([l l] [ls ls] [c 0])
(if (null? l)
c
(loop (cdr l) (map cdr ls)
(if (apply f (car l) (map car ls)) (add1 c) c))))
(raise-arguments-error 'count "all lists must have same size")))
(let loop ([l l] [c 0])
(if (null? l) c (loop (cdr l) (if (f (car l)) (add1 c) c))))))
;; Originally from srfi-1 -- shares common tail with the input when possible
;; (define (partition f l)
;; (unless (and (procedure? f) (procedure-arity-includes? f 1))
;; (raise-argument-error 'partition "procedure (arity 1)" f))
;; (unless (list? l) (raise-argument-error 'partition "proper list" l))
;; (let loop ([l l])
;; (if (null? l)
;; (values null null)
;; (let* ([x (car l)] [x? (f x)])
;; (let-values ([(in out) (loop (cdr l))])
;; (if x?
;; (values (if (pair? out) (cons x in) l) out)
;; (values in (if (pair? in) (cons x out) l))))))))
;; But that one is slower than this, probably due to value packaging
(define (partition pred l)
(unless (and (procedure? pred) (procedure-arity-includes? pred 1))
(raise-argument-error 'partition "(any/c . -> . any/c)" 0 pred l))
(unless (list? l) (raise-argument-error 'partition "list?" 1 pred l))
(let loop ([l l] [i '()] [o '()])
(if (null? l)
(values (reverse i) (reverse o))
(let ([x (car l)] [l (cdr l)])
(if (pred x) (loop l (cons x i) o) (loop l i (cons x o)))))))
;; similar to in-range, but returns a list
(define range
(case-lambda
[(end) (for/list ([i (in-range end)]) i)]
[(start end) (for/list ([i (in-range start end)]) i)]
[(start end step) (for/list ([i (in-range start end step)]) i)]))
(define append-map
(case-lambda [(f l) (apply append (map f l))]
[(f l1 l2) (apply append (map f l1 l2))]
[(f l . ls) (apply append (apply map f l ls))]))
;; this is an exact copy of `filter' in racket/private/list, with the
;; `if' branches swapped.
(define (filter-not f list)
(unless (and (procedure? f)
(procedure-arity-includes? f 1))
(raise-argument-error 'filter-not "(any/c . -> . any/c)" 0 f list))
(unless (list? list)
(raise-argument-error 'filter-not "list?" 1 f list))
;; accumulating the result and reversing it is currently slightly
;; faster than a plain loop
(let loop ([l list] [result null])
(if (null? l)
(reverse result)
(loop (cdr l) (if (f (car l)) result (cons (car l) result))))))
;; Fisher-Yates Shuffle
(define (shuffle l)
(define a (make-vector (length l)))
(for ([x (in-list l)] [i (in-naturals)])
(define j (random (add1 i)))
(unless (= j i) (vector-set! a i (vector-ref a j)))
(vector-set! a j x))
(vector->list a))
;; This implements an algorithm known as "Ord-Smith". (It is described in a
;; paper called "Permutation Generation Methods" by Robert Sedgewlck, listed as
;; Algorithm 8.) It has a number of good properties: it is very fast, returns
;; a list of results that has a maximum number of shared list tails, and it
;; returns a list of reverses of permutations in lexical order of the input,
;; except that the list itself is reversed so the first permutation is equal to
;; the input and the last is its reverse. In other words, (map reverse
;; (permutations (reverse l))) is a list of lexicographically-ordered
;; permutations (but of course has no shared tails at all -- I couldn't find
;; anything that returns sorted results with shared tails efficiently). I'm
;; not listing these features in the documentation, since I'm not sure that
;; there is a need to expose them as guarantees -- but if there is, then just
;; revise the docs. (Note that they are tested.)
;;
;; In addition to all of this, it has just one loop, so it is easy to turn it
;; into a "streaming" version that spits out the permutations one-by-one, which
;; could be used with a "callback" argument as in the paper, or can implement
;; an efficient `in-permutations'. It uses a vector to hold state -- it's easy
;; to avoid this and use a list instead (in the loop, the part of the c vector
;; that is before i is all zeros, so just use a list of the c values from i and
;; on) -- but that makes it slower (by about 70% in my timings).
(define (swap+flip l i j)
;; this is the main helper for the code: swaps the i-th and j-th items, then
;; reverses items 0 to j-1; with special cases for 0,1,2 (which are
;; exponentially more frequent than others)
(case j
[(0) `(,(cadr l) ,(car l) ,@(cddr l))]
[(1) (let ([a (car l)] [b (cadr l)] [c (caddr l)] [l (cdddr l)])
(case i [(0) `(,b ,c ,a ,@l)]
[else `(,c ,a ,b ,@l)]))]
[(2) (let ([a (car l)] [b (cadr l)] [c (caddr l)] [d (cadddr l)]
[l (cddddr l)])
(case i [(0) `(,c ,b ,d ,a ,@l)]
[(1) `(,c ,d ,a ,b ,@l)]
[else `(,d ,b ,a ,c ,@l)]))]
[else (let loop ([n i] [l1 '()] [r1 l])
(if (> n 0) (loop (sub1 n) (cons (car r1) l1) (cdr r1))
(let loop ([n (- j i)] [l2 '()] [r2 (cdr r1)])
(if (> n 0) (loop (sub1 n) (cons (car r2) l2) (cdr r2))
`(,@l2 ,(car r2) ,@l1 ,(car r1) ,@(cdr r2))))))]))
(define (permutations l)
(cond [(not (list? l)) (raise-argument-error 'permutations "list?" 0 l)]
[(or (null? l) (null? (cdr l))) (list l)]
[else
(define N (- (length l) 2))
;; use a byte-string instead of a vector -- doesn't matter much for
;; speed, but permutations of longer lists are impractical anyway
(when (> N 254) (error 'permutations "input list too long: ~e" l))
(define c (make-bytes (add1 N) 0))
(let loop ([i 0] [acc (list (reverse l))])
(define ci (bytes-ref c i))
(cond [(<= ci i) (bytes-set! c i (add1 ci))
(loop 0 (cons (swap+flip (car acc) ci i) acc))]
[(< i N) (bytes-set! c i 0)
(loop (add1 i) acc)]
[else acc]))]))
(define (in-permutations l)
(cond [(not (list? l)) (raise-argument-error 'in-permutations "list?" 0 l)]
[(or (null? l) (null? (cdr l))) (in-value l)]
[else
(define N (- (length l) 2))
(when (> N 254) (error 'permutations "input list too long: ~e" l))
(define c (make-bytes (add1 N) 0))
(define i 0)
(define cur (reverse l))
(define (next)
(define r cur)
(define ci (bytes-ref c i))
(cond [(<= ci i) (bytes-set! c i (add1 ci))
(begin0 (swap+flip cur ci i) (set! i 0))]
[(< i N) (bytes-set! c i 0)
(set! i (add1 i))
(next)]
[else #f]))
(in-producer (λ() (begin0 cur (set! cur (next)))) #f)]))
;; mk-min : (number number -> boolean) symbol (X -> real) (listof X) -> X
(define (mk-min cmp name f xs)
(unless (and (procedure? f)
(procedure-arity-includes? f 1))
(raise-argument-error name "(any/c . -> . real?)" 0 f xs))
(unless (and (list? xs)
(pair? xs))
(raise-argument-error name "(and/c list? (not/c empty?))" 1 f xs))
(let ([init-min-var (f (car xs))])
(unless (real? init-min-var)
(raise-result-error name "real?" init-min-var))
(let loop ([min (car xs)]
[min-var init-min-var]
[xs (cdr xs)])
(cond
[(null? xs) min]
[else
(let ([new-min (f (car xs))])
(unless (real? new-min)
(raise-result-error name "real?" new-min))
(cond
[(cmp new-min min-var)
(loop (car xs) new-min (cdr xs))]
[else
(loop min min-var (cdr xs))]))]))))
(define (argmin f xs) (mk-min < 'argmin f xs))
(define (argmax f xs) (mk-min > 'argmax f xs))