From 1b3d763cc69e9635e8f6952ad6ca4f2ae070672e Mon Sep 17 00:00:00 2001 From: Marco Date: Tue, 20 Aug 2024 16:45:14 +0200 Subject: [PATCH] sicp exercise 1.4 and various recursive algorithms --- exercise1-4.scm | 5 +++++ factorial.scm | 5 +++++ newton.scm | 22 ++++++++++++++++++++++ test-order-of-execution.scm | 37 +++++++++++++++++++++++++++++++++++++ 4 files changed, 69 insertions(+) create mode 100644 exercise1-4.scm create mode 100644 factorial.scm create mode 100644 newton.scm create mode 100644 test-order-of-execution.scm diff --git a/exercise1-4.scm b/exercise1-4.scm new file mode 100644 index 0000000..f933d9e --- /dev/null +++ b/exercise1-4.scm @@ -0,0 +1,5 @@ +(define (add-abs a b) + ((if (> b 0) + -) a b ) + ) + +(print (add-abs 3 -4)) diff --git a/factorial.scm b/factorial.scm new file mode 100644 index 0000000..f87da1d --- /dev/null +++ b/factorial.scm @@ -0,0 +1,5 @@ +(define (factorial n) + (cond ((= n 2) 2) + (else (* (factorial (- n 1)) n)))) + +(print (factorial 10000)) diff --git a/newton.scm b/newton.scm new file mode 100644 index 0000000..6d68ea8 --- /dev/null +++ b/newton.scm @@ -0,0 +1,22 @@ +(define (sqrt_iter new_guess last_guess x) + (if (good_enough? new_guess last_guess) + new_guess + (sqrt_iter (improve new_guess x) new_guess x) + ) +) + +(define (improve guess x) + (/ (+ guess (/ x guess)) 2)) + + +(define (good_enough? guess last_guess) + (< (absolute (- guess last_guess)) 0.000000000000001)) + +(define (absolute x) + (if (< x 0) + (- 0 x) + x)) + +(define (sqrt x) (sqrt_iter (/ x 2.0) x x)) + +(print (sqrt 2)) diff --git a/test-order-of-execution.scm b/test-order-of-execution.scm new file mode 100644 index 0000000..a42edba --- /dev/null +++ b/test-order-of-execution.scm @@ -0,0 +1,37 @@ +(define (mainstage-with-if x y) + (print "this is mainstage-with-if") + (if (< x y) (stage11 x) (stage21 y))) + +(define (mainstage-with-procedure-if x y) + (print "this is mainstage-with-if") + (procedure-if (< x y) (stage11 x) (stage21 y))) + +(define (stage11 x) + (print "this is stage11") + (stage12 x)) + +(define (stage21 x) + (print "this is stage21") + (stage22 x)) + +(define (stage12 x) + (print "this is stage12") + (stage13 x)) + +(define (stage22 x) + (print "this is stage22") + (stage23 x)) + +(define (stage13 x) + (print "this is stage13") + x) + +(define (stage23 x) + (print "this is stage23") + x) + +(define (procedure-if predicate then-clause else-clause) + (cond (predicate then-clause) (else else-clause))) + +(print (mainstage-with-if 1 2)) +(print (mainstage-with-procedure-if 1 2))