Skip to content

Instantly share code, notes, and snippets.

@chelseatroy
Created October 30, 2019 15:21
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 chelseatroy/5488e61ca4e9b6195801e8b113defc74 to your computer and use it in GitHub Desktop.
Save chelseatroy/5488e61ca4e9b6195801e8b113defc74 to your computer and use it in GitHub Desktop.
Accumulate
; 2.33
(define (accumulate op initial items) ; accumulate also referred to as "reduce"
(if (null? items)
initial
(op (car items) (accumulate op initial (cdr items)))))
; Defining collection operations in terms of accumulate
(define (append seq1 seq2)
(accumulate cons seq2 seq1))
(define (map proc items)
(accumulate (lambda (x y) (cons (proc x) y)) '() items))
(define (filter proc items)
(accumulate (lambda (x y) (if (proc x) (cons x y) y)) '() items))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment