cps: add some begins
[lambda.git] / hints / cps_hint_3.mdwn
1 This function is developed in *The Seasoned Schemer* pp. 84-89. It accepts an atom `a` and a list `lst` and returns `lst` with the leftmost occurrence of `a`, if any, removed. Occurrences of `a` will be found no matter how deeply embedded.
2
3         #lang racket
4         
5         (define (atom? x)
6           (and (not (pair? x)) (not (null? x))))
7         
8         (define gamma
9           (lambda (a lst)
10             (letrec ([aux (lambda (l k)
11                             (cond
12                               [(null? l) (k 'notfound)]
13                               [(eq? (car l) a) (cdr l)]
14                               [(atom? (car l)) (cons (car l) (aux (cdr l) k))]
15                               [else
16                                ; when (car l) exists but isn't an atom, we try to remove a from (car l)
17                                ; if we succeed we prepend the result to (cdr l) and stop
18                                (let ([car2 (let/cc k2
19                                              ; calling k2 with val will bind car2 to val and continue with the (cond ...) block below
20                                              (aux (car l) k2))])
21                                  (cond
22                                    ; if a wasn't found in (car l) then prepend (car l) to the result of removing a from (cdr l)
23                                    [(eq? car2 'notfound) (cons (car l) (aux (cdr l) k))]
24                                    ; else a was found in (car l)
25                                    [else (cons car2 (cdr l))]))]))]
26                      [lst2 (let/cc k1
27                              ; calling k1 with val will bind lst2 to val and continue with the (cond ...) block below
28                              (aux lst k1))])
29               (cond
30                 ; was no atom found in lst?
31                 [(eq? lst2 'notfound) lst]
32                 [else lst2]))))
33         
34         (gamma 'a '(((a b) ()) (c (d ()))))       ; ~~> '(((b) ()) (c (d ())))
35         (gamma 'a '((() (a b) ()) (c (d ()))))    ; ~~> '((() (b) ()) (c (d ())))
36         (gamma 'a '(() (() (a b) ()) (c (d ())))) ; ~~> '(() (() (b) ()) (c (d ())))
37         (gamma 'c '((() (a b) ()) (c (d ()))))    ; ~~> '((() (a b) ()) ((d ())))
38         (gamma 'c '(() (() (a b) ()) (c (d ())))) ; ~~> '(() (() (a b) ()) ((d ())))
39         (gamma 'x '((() (a b) ()) (c (d ()))))    ; ~~> '((() (a b) ()) (c (d ())))
40