Skip to content

Instantly share code, notes, and snippets.

@chelseatroy
Created October 30, 2019 15:22
Show Gist options
  • Select an option

  • Save chelseatroy/ef547b733e95f4cca985d011fc7303e1 to your computer and use it in GitHub Desktop.

Select an option

Save chelseatroy/ef547b733e95f4cca985d011fc7303e1 to your computer and use it in GitHub Desktop.
Fold Left and Fold Right
; 2.38
(define (fold-right op initial sequence)
(accumulate op initial sequence))
(define (fold-left op initial sequence)
(define (iter result rest)
(if (null? rest)
result
(iter (op result (car rest))
(cdr rest))))
(iter initial sequence))
(fold-right / 1 (list 1 2 3)) ;--------> 1 1/2
(fold-left / 1 (list 1 2 3)) ;--------> 1/6
(fold-right list null (list 1 2 3)) ;--> '(1 (2 (3 ())))
(fold-left list null (list 1 2 3)) ;--> '(((() 1) 2) 3)
; 2.39
(define (reverse sequence)
(fold-right (lambda x y) (append y (list x)) null sequence))
(define (reverse sequence)
(fold-left (lambda x y) (cons (y x)) null sequence))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment