]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/distinct.rkt
solutions to 4.38, 4.39 and 4.40
[sicp.git] / src / sicp / distinct.rkt
1 #lang racket
2
3 (provide distinct?)
4
5 (define (distinct? xs)
6   (let loop [(s (set))
7              (r xs)]
8     (cond [(empty? r) #t]
9           [(set-member? s (first r)) #f]
10           [else (loop (set-add s (first r)) (rest r))])))
11
12 (module+ test
13   (require rackunit)
14   
15   (check-equal? (distinct? '()) #t)
16   (check-equal? (distinct? '(1)) #t)
17   (check-equal? (distinct? '(1 2)) #t)
18   (check-equal? (distinct? '(1 1)) #f)
19   (check-equal? (distinct? '(1 2 3)) #t)
20   (check-equal? (distinct? '(1 2 3 3 2)) #f)
21   (check-equal? (distinct? '(a b)) #t)
22   (check-equal? (distinct? '(a b a)) #f)
23   (check-equal? (distinct? '(a b c c)) #f)
24   (check-equal? (distinct? '(1 2 3 4)) #t)
25   (check-equal? (distinct? '(1 2 3 4 5)) #t)
26   (check-equal? (distinct? '(1 (2 3) 4 2 3)) #t))