learning-sicp

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

commit 660a9ffb718ce541994fb28d2949350d0a1ae952
parent d2155a455673019bc6608fdf7495a05d987509ce
Author: Yuval Langer <yuval.langer@gmail.com>
Date:   Sun, 26 Mar 2023 19:16:17 +0300

Add utility procedures and tests.

Diffstat:
Autils-tests.scm | 32++++++++++++++++++++++++++++++++
Autils.scm | 29+++++++++++++++++++++++++++++
2 files changed, 61 insertions(+), 0 deletions(-)

diff --git a/utils-tests.scm b/utils-tests.scm @@ -0,0 +1,32 @@ +(define-library (utils-tests) + (import (srfi srfi-64)) + (import (scheme base)) + (import (sicp utils)) + + (begin + (test-begin "enumerate-interval") + (test-equal + '() + (enumerate-interval 1 0)) + (test-equal + '(1) + (enumerate-interval 1 1)) + (test-equal + '(1 2) + (enumerate-interval 1 2)) + (test-equal + '(1 2 3) + (enumerate-interval 1 3)) + (test-end "enumerate-interval") + + (test-begin "accumulate") + (test-equal + 15 + (accumulate + 0 '(1 2 3 4 5))) + (test-equal + 120 + (accumulate * 1 '(1 2 3 4 5))) + (test-equal + '(1 2 3 4 5) + (accumulate cons '() '(1 2 3 4 5))) + (test-end "accumulate"))) diff --git a/utils.scm b/utils.scm @@ -0,0 +1,29 @@ +(define-library (sicp utils) + (import (scheme base)) + (import (srfi srfi-1)) + (import (srfi srfi-64)) + (export accumulate enumerate-interval flatmap) + + (begin + (define (enumerate-interval low high) +;; (iota (- high low -1) low) +;; From 2.2.3 Sequences as Conventional Interfaces + (if (> low high) + '() + (cons low + (enumerate-interval (+ 1 low) + high)))) + + (define (accumulate op initial sequence) + ;; From 2.2.3 Sequences as Conventional Interfaces + (if (null? sequence) + initial + (op (car sequence) + (accumulate op + initial + (cdr sequence))))) + + (define (flatmap proc seq) + (accumulate append + '() + (map proc seq)))))