; flipping pancakes
(define (flip n xs)
(let loop ((n n) (xs xs) (ys '()))
(if (or (null? xs) (zero? n)) (append ys xs)
(loop (- n 1) (cdr xs) (cons (car xs) ys)))))
(define (find-max n xs)
(let loop ((n n) (xs xs) (k 0) (mx 0) (mk 0))
(cond ((or (zero? n) (null? xs)) mk)
((< mx (car xs)) (loop (- n 1) (cdr xs) (+ k 1) (car xs) (+ k 1)))
(else (loop (- n 1) (cdr xs) (+ k 1) mx mk)))))
(define (pancake xs)
(let loop ((k (length xs)) (xs xs))
(let* ((j k) (i (find-max j xs)))
(if (= j 1) xs
(loop (- k 1) (flip j (flip i xs)))))))
(display (pancake '(7 2 9 4 6 1 3 8 5)))