Skip to content

Instantly share code, notes, and snippets.

@d11wtq
Created June 16, 2012 12:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d11wtq/2941181 to your computer and use it in GitHub Desktop.
Save d11wtq/2941181 to your computer and use it in GitHub Desktop.
;; This was damn hard.
;;
;; One of the exercises near the end of The Little Schemer requires defining
;; a function that uses a collector to remove odd numbers, recursively from
;; a list, sum the odd numbers and multiple the even numbers.
;;
;; This is it.
;;
;; It requires currying lambdas one inside another to deal with the recursion
;; in the collector function.
(define (evens-only*&co list col-fn)
(cond
((null? list)
(col-fn '() 1 0))
((list? (car list))
(evens-only*&co (car list)
(lambda (v x y)
(evens-only*&co (cdr list)
(lambda (vv xx yy)
(col-fn (cons v vv)
(* x xx) (+ y yy)))))))
((odd? (car list))
(evens-only*&co (cdr list)
(lambda (v x y)
(col-fn v
x (+ (car list) y)))))
(else
(evens-only*&co (cdr list)
(lambda (v x y)
(col-fn (cons (car list) v)
(* (car list) x) y))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment