Skip to content

Instantly share code, notes, and snippets.

@monmon
Created November 12, 2012 03:00
Show Gist options
  • Select an option

  • Save monmon/4057259 to your computer and use it in GitHub Desktop.

Select an option

Save monmon/4057259 to your computer and use it in GitHub Desktop.
SICP q2.38
(define nil '())
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))
(define fold-right accumulate)
(define (fold-left op initial sequence)
(define (iter result rest)
(if (null? rest)
result
(iter (op result (car rest))
(cdr rest))))
(iter initial sequence))
(print (fold-right / 1 (list 1 2 3))) ; 3/2 = 1/(2/(3/1))
(print (fold-left / 1 (list 1 2 3))) ; 1/6 = ((1/1)/2)/3
(print (fold-right list nil (list 1 2 3))) ; (1 (2 (3 ())))
(print (fold-left list nil (list 1 2 3))) ; (((() 1) 2) 3)
; 交換法則が成り立てば同じ値になる
@monmon
Copy link
Copy Markdown
Author

monmon commented Nov 14, 2012

initialが単位元なら結合だけでいいよね

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment