Created
February 11, 2010 07:38
-
-
Save valvallow/301312 to your computer and use it in GitHub Desktop.
The Seasoned Schemer, sum-of-prefixes
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
;; sum-of-prefixes | |
; (2 1 9 17 0) -> (2 3 12 29 29) | |
; (1 1 1 1 1) -> (1 2 3 4 5) | |
; letrec | |
(define sum-of-prefixes | |
(lambda (tup) | |
(letrec ((f (lambda (t p) | |
(if (null? t) | |
'() | |
(let ((v (+ (car t) p))) | |
(cons v | |
(f (cdr t) v))))))) | |
(f tup 0)))) | |
; fold | |
(define sum-of-prefixes | |
(lambda (tup) | |
(reverse (fold (lambda (e r) | |
(cons (+ e (if (null? r) | |
0 | |
(car r))) | |
r)) | |
'() | |
tup)))) | |
; pair-fold | |
(use srfi-1) | |
(define sum-of-prefixes | |
(lambda (tup) | |
(reverse (pair-fold (lambda (rest ret) | |
(cons (+ (car rest) | |
(if (null? ret) | |
0 | |
(car ret))) | |
ret)) | |
'() | |
tup)))) | |
(define sum-of-prefixes-b | |
(lambda (sonssf tup) | |
(if (null? tup) | |
'() | |
(let ((a (+ sonssf (car tup)))) | |
(cons a (sum-of-prefixes-b a (cdr tup))))))) | |
(define sum-of-prefixes | |
(lambda (tup) | |
(sum-of-prefixes-b 0 tup))) | |
(sum-of-prefixes '(2 1 9 17 0)) | |
; -> (2 3 12 29 29) | |
(sum-of-prefixes '(1 1 1 1 1)) | |
; -> (1 2 3 4 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment