week9: {get,set}_state -> _store
[lambda.git] / hints / cps_hint_1.mdwn
1 This function is developed in *The Seasoned Schemer* pp. 55-60. It accepts an atom `a` and a list of atoms `lst`, and returns the part of `lst` following the last occurrence of `a`. If `a` is not in `lst`, it returns `lst` unaltered.
2
3         #lang racket
4         
5         (define (atom? x)
6           (and (not (pair? x)) (not (null? x))))
7         
8         (define alpha
9           (lambda (a lst)
10             (let/cc k ; calling k with val will immediately return val from the call to alpha
11               (letrec ([aux (lambda (l)
12                               (cond
13                                 [(null? l) '()]
14                                 [(eq? (car l) a)
15                                  ; we abandon any waiting recursive (aux ...) calls, and instead immediately return (aux (cdr l))
16                                  ; ...since Scheme is call-by-value, (aux (cdr l)) will be evaluated first, and
17                                  ; any calls to k therein will come first (and the pending (k ...) here will be abandoned)
18                                  (k (aux (cdr l)))]
19                                 [else (cons (car l) (aux (cdr l)))]))])
20                 (aux lst)))))
21         
22         
23         (alpha 'a '(a b c a d e f)) ; ~~> '(d e f)
24         (alpha 'x '(a b c a d e f)) ; ~~> '(a b c a d e f)
25         (alpha 'f '(a b c a d e f)) ; ~~> '()
26         (alpha 'a '(a b c x d e f)) ; ~~> '(b c x d e f)
27