Skip to content

Instantly share code, notes, and snippets.

@tautologico
Created July 23, 2017 22:40
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 tautologico/579d38aefa58641a621ee995bc260106 to your computer and use it in GitHub Desktop.
Save tautologico/579d38aefa58641a621ee995bc260106 to your computer and use it in GitHub Desktop.
Product with exit for 0
;; product with break and O(1) case for a zero operand
;; call/cc
(define (product-cc ls)
(call-with-current-continuation
(lambda (break)
(cond ((null? ls) 1)
((= (car ls) 0) (break 0))
(else (* (car ls) (product-cc (cdr ls))))))))
;; continuation-passing style
(define (product-cps ls k break)
(cond ((null? ls) (k 1))
((= (car ls) 0) (break 0))
(else (product-cps (cdr ls) (lambda (x) (k (* (car ls) x))) break))))
(define (product-cps2 ls k)
(let ((break k))
(let f ((ls ls) (k k))
(cond ((null? ls) (k 1))
((= (car ls) 0) (break 0))
(else (f (cdr ls)
(lambda (x)
(k (* (car ls) x)))))))))
(define (product ls)
(product-cps ls (lambda (x) x) (lambda (x) x)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment