add cps_hint_*
[lambda.git] / topics / cps_hint_1.mdwn
diff --git a/topics/cps_hint_1.mdwn b/topics/cps_hint_1.mdwn
new file mode 100644 (file)
index 0000000..985ba18
--- /dev/null
@@ -0,0 +1,27 @@
+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.
+
+       #lang racket
+       
+       (define (atom? x)
+         (and (not (pair? x)) (not (null? x))))
+       
+       (define alpha
+         (lambda (a lst)
+           (let/cc k ; calling k with val will immediately return val from the call to alpha
+             (letrec ([aux (lambda (l)
+                             (cond
+                               [(null? l) '()]
+                               [(eq? (car l) a)
+                                ; we abandon any waiting recursive (aux ...) calls, and instead immediately return (aux (cdr l))
+                                ; ...since Scheme is call-by-value, (aux (cdr l)) will be evaluated first, and
+                                ; any calls to k therein will come first (and the pending (k ...) here will be abandoned)
+                                (k (aux (cdr l)))]
+                               [else (cons (car l) (aux (cdr l)))]))])
+               (aux lst)))))
+       
+       
+       (alpha 'a '(a b c a d e f)) ; ~~> '(d e f)
+       (alpha 'x '(a b c a d e f)) ; ~~> '(a b c a d e f)
+       (alpha 'f '(a b c a d e f)) ; ~~> '()
+       (alpha 'a '(a b c x d e f)) ; ~~> '(b c x d e f)
+