sicp

sicp sandbox.
git clone git://git.ricketyspace.net/sicp.git
Log | Files | Refs

commit 94758d69d5ef1eccf39842fb806e736b31387fa6
parent 1375cccf75aee17bbe576a744583ed9e7f7d939e
Author: rsiddharth <rsiddharth@ninthfloor.org>
Date:   Sat, 12 Mar 2016 11:37:03 -0500

Tried answering 1.1.6

Diffstat:
one/six.scm | 36++++++++++++++++++++++++++++++++++++
sicp.org | 11+++++++++++
2 files changed, 47 insertions(+), 0 deletions(-)

diff --git a/one/six.scm b/one/six.scm @@ -0,0 +1,36 @@ +(define-module (one six) + #:export (sqrt-sicp sqrt-nif square good-enough? new-if improve)) + +(define (square x) + (* x x)) + +(define (good-enough? guess x) + (< (abs (- (square guess) x)) 0.001)) + +(define (average x y) + (/ (+ x y) 2)) + +(define (improve guess x) + (average guess (/ x guess))) + +(define (new-if predicate then-clause else-clause) + (cond (predicate then-clause) + (else else-clause))) + +(define (sqrt-iter guess x) + (if (good-enough? guess x) + guess + (sqrt-iter (improve guess x) + x))) + +(define (sqrt-iter-nif guess x) + (new-if (good-enough? guess x) + guess + (sqrt-iter-nif (improve guess x) + x))) + +(define (sqrt-sicp x) + (sqrt-iter 1.0 x)) + +(define (sqrt-nif x) + (sqrt-iter-nif 1.0 x)) diff --git a/sicp.org b/sicp.org @@ -46,3 +46,14 @@ order*, the expression will be expanded to #+END_SRC and will evaluate to ~0~. +*** 6 + If I've understood it correctly, scheme uses applicative-order + evaluation, meaning, it evaluates the operands before appling the + procedure. + + In the case when ~new-if~ used in the ~sqrt-iter~ procedure, the + operands/arguments for the ~new-if~ -- ~(good-enough? guess x)~, + ~guess~, ~(sqrt-iter (improve guess x) x)~ -- are evaluated. Due + to the last operand, which is a call to the ~sqrt-iter~ procedure, + we get into infinite loop of evaluating the ~sqrt-iter~ procedure + again and again.