learning-sicp

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

commit 13dba597cc44a16ce58771aa698f3f8d3a16b598
parent 6dc652e101ad8cc62c38d77f3de9a63a92fe1d69
Author: Yuval Langer <yuval.langer@gmail.com>
Date:   Sun, 16 Apr 2023 15:47:55 +0300

Add solutions to exercise 3.18 and exercise 3.19.

Diffstat:
Asicp/solutions/3_18.scm | 17+++++++++++++++++
Asicp/solutions/3_19.scm | 21+++++++++++++++++++++
Asicp/tests/3_18.scm | 25+++++++++++++++++++++++++
Asicp/tests/3_19.scm | 25+++++++++++++++++++++++++
4 files changed, 88 insertions(+), 0 deletions(-)

diff --git a/sicp/solutions/3_18.scm b/sicp/solutions/3_18.scm @@ -0,0 +1,17 @@ +(define-library (sicp solutions 3_18) + (import (scheme base)) + (export cyclic?) + + (begin + (define (cyclic? l) + (define (cyclic?' l known-pairs) + (cond + ((null? l) #f) + ((pair? l) + (if (memq l known-pairs) + #t + (cyclic?' (cdr l) + (cons l known-pairs)))) + (else #f))) + + (cyclic?' l '())))) diff --git a/sicp/solutions/3_19.scm b/sicp/solutions/3_19.scm @@ -0,0 +1,21 @@ +(define-library (sicp solutions 3_18) + (import (scheme base)) + (export cyclic?) + + (begin + (define (cyclic? l) + + (define (cyclic?' tortoise hare) + (cond + ((or (null? hare) + (null? (cdr hare)) + (null? (cddr hare))) + #f) + (if (memq tortoise hare) + #t + (cyclic?' (cdr tortoise) + (cddr hare))))) + + (if (null? l) + #f + (cyclic? l (cdr l)))))) diff --git a/sicp/tests/3_18.scm b/sicp/tests/3_18.scm @@ -0,0 +1,25 @@ +(define-library (sicp tests 3_18) + (import (scheme base)) + (import (srfi :1)) + (import (srfi :64)) + (import (only (sicp solutions 3_18) cyclic?)) + + (begin + (test-begin "3.18") + + (define a (list 1 2 3)) + + (define b + (let ([a (list 1 2 3)]) + (set-cdr! (last-pair a) a) + a)) + + (test-equal + #f + (cyclic? a)) + + (test-equal + #t + (cyclic? b)) + + (test-end "3.18"))) diff --git a/sicp/tests/3_19.scm b/sicp/tests/3_19.scm @@ -0,0 +1,25 @@ +(define-library (sicp tests 3_18) + (import (scheme base)) + (import (srfi :1)) + (import (srfi :64)) + (import (only (sicp solutions 3_18) cyclic?)) + + (begin + (test-begin "3.18") + + (define a (list 1 2 3)) + + (define b + (let ([a (list 1 2 3)]) + (set-cdr! (last-pair a) a) + a)) + + (test-equal + #f + (cyclic? a)) + + (test-equal + #t + (cyclic? b)) + + (test-end "3.18")))