sicp-solutions/ex-2.38.scm
Petar Kapriš 2ca5e73a27 Add solutions to exercises from subsection 2.2.3
Notes:
The exercise 2.37 on Hexlet's site has an error, noted in the comments.
Also, their page for exercise 2.38 should probably have 0 tests.

And finally, I did not calculate the exact number in the final exercise
2.43, but I included a relevant discussion.
2025-02-12 16:16:13 +01:00

22 lines
655 B
Scheme

#lang sicp
(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 / 1 (list 1 2 3)) -> (1/(2/(3/1))) = 3/2
; (fold-left / 1 (list 1 2 3)) -> (((1/1)/2)/3) = 1/6
; (fold-right list nil (list 1 2 3)) -> (1 (2 (3 ())))
; (fold-left list nil (list 1 2 3)) -> (((() 1) 2) 3)
; in order to produce the same results, the operation
; must be associative.