Chapter 2, Building Abstractions with Data

Section - 2.2 - Hierarchical Data and the Closure Property

Exercise 2.38


Procedures for fold-left and fold-right:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
(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:

.

Eg: If and :

.

Fold-Left:

.

Eg: If and :

.

1
2
3
4
5
6
7
8
9
10
11
12
> (fold-right / 1 (list 1 2 3))
3/2

>  (fold-left / 1 (list 1 2 3))
1/6

> (display (fold-right list nil (list 1 2 3)))
(1 (2 (3 ())))

> (display (fold-left list nil (list 1 2 3)))
(((() 1) 2) 3)
> 

If fold-right and fold-left produce same values then:

.

For eg: if and :

.

Clearly this property is called associative in mathematics.