#lang racket
(define (fold-right op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(fold-right op initial (cdr 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 + 0 (list 1 2 3))
(fold-left + 0 (list 1 2 3))
(fold-right / 1 (list 1 2 3))
(fold-left / 1 (list 1 2 3))
(fold-right list null (list 1 2 3))
(fold-left list null (list 1 2 3))
运行结果
6
6
3/2
1/6
'(1 (2 (3 ())))
'(((() 1) 2) 3)
当op运行具有交换律时,fold-right和fold-left的运算结果是一样的,也就是
当
等
式
a
o
p
b
=
b
o
p
a
成
立
,
结
果
一
致
当等式a \ \ op\ \ b = b\ \ op\ \ a成立,结果一致
当等式a op b=b op a成立,结果一致