Last active
August 29, 2015 14:02
-
-
Save keyvanakbary/e700a525af388c17859c to your computer and use it in GitHub Desktop.
Continuation-passing style
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; calculate the sum of odd numbers, the product of even ones and a list of the odds | |
; example extracted from the book "The Little Schemer" | |
; more info here http://stackoverflow.com/questions/10692449/the-little-schemer-evens-onlyco | |
(defn evens-only*&co [l col] | |
(cond | |
(empty? l) (col `() 1 0) | |
(number? (first l)) | |
(cond | |
(even? (first l)) (evens-only*&co | |
(rest l) | |
(fn [newl product sum] | |
(col (cons (first l) newl) | |
(* (first l) product) sum))) | |
:else (evens-only*&co | |
(rest l) | |
(fn [newl product sum] | |
(col newl product (+ (first l) sum))))) | |
:else (evens-only*&co | |
(first l) | |
(fn [newl product sum] | |
(evens-only*&co (rest l) | |
(fn [dnewl dproduct dsum] | |
(col (cons newl dnewl) | |
(* product dproduct) | |
(+ sum dsum)))))))) | |
; collector, how to build the results | |
(def the-last-friend | |
(fn [newl product sum] | |
(cons sum (cons product newl)))) | |
(evens-only*&co `(1 (1 1 2) 2 1 3 2) the-last-friend) | |
; (7 8 (2) 2 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment