Created
July 23, 2017 22:40
-
-
Save tautologico/579d38aefa58641a621ee995bc260106 to your computer and use it in GitHub Desktop.
Product with exit for 0
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
;; 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