learning-sicp

My embarrassing half assed SICP run.
Log | Files | Refs

commit 745256649139b2a95b7b7290242e6b87932f341d
parent f762fbacedb2279d361f69354c6661df154741c4
Author: Yuval Langer <yuval.langer@gmail.com>
Date:   Mon, 13 Mar 2023 08:03:11 +0200

Add a few solutions up to exercise 2.41.

Diffstat:
Mguile.scm | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
1 file changed, 77 insertions(+), 11 deletions(-)

diff --git a/guile.scm b/guile.scm @@ -2672,7 +2672,35 @@ Iterative. ;; Exercise 2.40 +(define (flatmap proc seq) + (accumulate append + '() + (map proc seq))) + +(define (unique-pairs n) + (flatmap (lambda (i) + (map (lambda (j) + (list i j)) + (enumerate-interval 1 (1- i)))) + (enumerate-interval 1 n))) + (define (exercise-2.40) + (define (remove item seqeunce) + (filter (lambda (x) + (not (equal? x + item))) + sequence)) + + (define (permutations s) + (if (null? s) + (list '()) + (flatmap (lambda (x) + (map (lambda (p) + (cons x p)) + (permutations (remove x + s)))) + s))) + (define (f n) (accumulate append @@ -2683,12 +2711,6 @@ Iterative. (enumerate 1 (1- i)))) (enumerate-interval 1 n)))) - (define (flatmap proc seq) - (accumulate append - '() - (map proc - seq))) - (define (g n) (flatmap (lambda (x) x) (enumerate-interval 1 n))) @@ -2704,14 +2726,58 @@ Iterative. (define (prime-sum-pairs n) (map make-pair-sum + (filter + prime-sum? + (flatmap + (lambda (i) + (map (lambda (j) + (list i j)) + (enumerate-interval 1 (1- i)))) + (enumerate-interval 1 n))))) + + (define (my-prime-sum-pairs n) + (map make-pair-sum (filter prime-sum? - (flatmap (lambda (i) - (list i j)) - (enumerate-interval 1 - (1- i)))))) - + (unique-pairs n)))) (test-begin "2.40") + (test-equal + '((2 1) + (3 1) (3 2) + (4 1) (4 2) (4 3)) + (unique-pairs 4)) + (test-equal + (prime-sum-pairs 20) + (my-prime-sum-pairs 20)) (test-end "2.40")) (exercise-2.40) + +(define (exercise-2.41) + (define (unique-triples n) + (flatmap (lambda (pair) + (map (lambda (k) + (append pair (list k))) + (enumerate-interval 1 (1- (cadr pair))))) + (unique-pairs n))) + + (define ratsui + '((3 2 1) + (4 2 1) + (4 3 1) + (4 3 2) + (5 2 1) + (5 3 1) + (5 3 2) + (5 4 1) + (5 4 2) + (5 4 3))) + + + (test-begin "2.41") + (test-equal + ratsui + (unique-triples 5)) + (test-end "2.41")) + +(exercise-2.41)