Skip to content

Instantly share code, notes, and snippets.

@jimmyp
Last active December 17, 2015 12:08
Show Gist options
  • Save jimmyp/5607180 to your computer and use it in GitHub Desktop.
Save jimmyp/5607180 to your computer and use it in GitHub Desktop.
SICP 1.1 Exercises
; 1.1
; What is the result of each of the follow expressions
; 10 => 10
; (+ 5 3 4) => 12
; (- 9 1) => 8
; (/ 6 2) => 3
; (+ (* 2 4) (- 4 6)) => (+ 8 -2) => 6
; (define a 3)
; (define b (+ a 1))
; (+ a b (* a b))
; => (+ 3 (+ 3 1) (* 3 (+ 3 1)))
; => (+ 3 4 (* 3 4))
; => (+ 3 4 12)
; => 19
; (if (and (> b a) (< b (* a b))) b a)
; => (if (and (> (+ 3 1) 3) (< (+ 3 1) (* 3 (+ 3 1)))) (+ 3 1) 3)
; => (if (and (> 4 3) (< 4 (* 3 4))) 4 3)
; => (if (and :t (< 4 12)) 4 3)
; => (if (and :t :t) 4 3)
; => 4
; 1.2
;(/ (+ 5 4 (- 2 (- 3 ( + 6 (/ 4 5))))) (* 3 (- 6 2) (- 2 7)))
; 1.3
(define (max1 a b c)
(cond ((and (> a b)(> b c)) a)
((and (> a b)(> c b)) a)
(else c)))
(define (max2 a b c)
(cond ((and (> a b)(> b c)) b)
((and (> a b)(> c b)) c)
(else b)))
(define (square x) (* x x))
(define (sum-square a b) (+ (square a) (square b)))
(define (sum-square-max2 a b c) (sum-square (max1 a b c)(max2 a b c)))
; 1.4
; Defines an operation with two formal parameters a and b. If b is greater than a is added to b. Otherwise a is subtracted from b.
; 1.5
; (define (p) (p))
; (define (test x y) (if (= x 0) 0 y))
; (test 0 (p))
; normal
; => (if (= 0 0) 0 (p))
; => (if :t 0 (p))
; => 0
; applicative
; (test 0 (p))
; => (test 0 (p))
; => (test 0 (p))
; 1.6
; Using applicative order this expression will never return as the argument for the else-clause parameter of new-if when evaluated causes an infinite loop
; 1.7
(define (good-enough? guess last-guess)
(< (/ (abs (- guess last-guess)) guess) 0.0001))
(define (average x y) (/ (+ x y) 2))
(define (improve guess x) (average guess (/ x guess)))
(define (sqrt-iter guess last-guess x)
(if (good-enough? guess last-guess)
guess
(sqrt-iter (improve guess x) guess x)))
(define (sqrt x) (sqrt-iter 1.0 0.9 x))
; 1.8
#lang racket
(define (good-enough? guess last-guess)
(< (/ (abs (- guess last-guess)) guess) 0.0001))
(define (square x) (* x x))
(define (improve guess x) (/ (+ (/ x (square guess)) (* 2 guess)) 3))
(define (cube-root-iter guess last-guess x)
(if (good-enough? guess last-guess)
guess
(cube-root-iter (improve guess x) guess x)))
(define (cube-root x) (cube-root-iter 1.0 0.9 x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment