forked from samirose/sicp-compiler-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlists.sls
73 lines (61 loc) · 1.95 KB
/
lists.sls
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
#!r6rs
(library
(lists)
(export partition-list index-of-equal first-duplicate make-list flatten-n all?
make-counted-set counted-set-add counted-set-count counted-set-unique-keys)
(import (rnrs base)
(rnrs lists))
(define (partition-list p l)
(let collect ((l l)
(lt '())
(lf '()))
(cond ((null? l) (cons (reverse lt) (reverse lf)))
((p (car l)) (collect (cdr l) (cons (car l) lt) lf))
(else (collect (cdr l) lt (cons (car l) lf))))))
(define (index-of-equal l e)
(let search ((l l) (i 0))
(cond ((null? l) #f)
((equal? (car l) e) i)
(else (search (cdr l) (+ i 1))))))
(define (first-duplicate l)
(let search ((l l))
(cond ((null? l) '())
((memq (car l) (cdr l)))
(else (search (cdr l))))))
(define (make-list e n)
(if (< n 0)
(error "Expected positive n -- make-list:" n)
(let loop ((l '()) (n n))
(if (= n 0)
l
(loop (cons e l) (- n 1))))))
(define (flatten-n n x)
(cond ((null? x) '())
((= n 0) x)
((pair? x)
(let ((head (car x)))
(if (pair? head)
(append
(flatten-n (- n 1) head)
(flatten-n n (cdr x)))
(cons head (flatten-n n (cdr x))))))
(else x)))
(define (all? p? l)
(cond ((null? l))
((p? (car l)) (all? p? (cdr l)))
(else #f)))
(define (make-counted-set) '())
(define (counted-set-add s key)
(let* ((existing (assq key s))
(count (if existing
(+ (cdr existing) 1)
1))
(new-head (cons key count))
(rest (filter (lambda (entry) (not (eq? key (car entry)))) s)))
(cons new-head rest)))
(define (counted-set-count s key)
(let ((existing (assq key s)))
(if existing (cdr existing) 0)))
(define (counted-set-unique-keys s)
(length s))
)