Skip to content

Instantly share code, notes, and snippets.

View mohanrajendran's full-sized avatar

Mohan Rajendran mohanrajendran

View GitHub Profile
@mohanrajendran
mohanrajendran / Exercise1-1.scm
Created July 6, 2014 23:26
SICP Exercise 1.1
10
; 10
(+ 5 3 4)
; 12
(- 9 1)
; 8
(/ 6 2)
@mohanrajendran
mohanrajendran / Exercise1-2.scm
Created July 6, 2014 23:26
SICP Exercise 1.2
(/ (+ 5 4 (- 2 (- 3 (+ 6 (/ 4 5)))))
(* 3 (- 6 2) (- 2 7)))
; -37/150
@mohanrajendran
mohanrajendran / Exercise1-3.scm
Created July 6, 2014 23:27
SICP Exercise 1.3
(define (sq x) (* x x))
; sq
(define (sumsq x y) (+ (sq x) (sq y)))
; sumsq
(define (largest2sq a b c)
(cond ((and (<= a b) (<= a c)) (sumsq b c))
((and (<= b a) (<= b c)) (sumsq a c))
(else (sumsq a b))))
@mohanrajendran
mohanrajendran / Exercise1-4.md
Last active August 29, 2015 14:03
SICP Exercise 1.4
(define (a-plus-abs-b a b)
  ((if (> b 0) + -) a b))

When the if function is evaluated, based on the condition, the operator + or - is applied on the operands a and b. If b > 0, + operator is used, evaluating to a+b. Otherwise, - operator is issued which yields a-b. Ultimately, we evaluate a+|b|.

@mohanrajendran
mohanrajendran / Exercise1-5.md
Last active August 29, 2015 14:03
SICP Exercise 1.5
(define (p) (p))

(define (test x y)
  (if (= x 0)
      0
      y))

(test 0 (p))
@mohanrajendran
mohanrajendran / Exercise1-6.md
Last active August 29, 2015 14:03
SICP Exercise 1.6
(define (new-if predicate then-clause else-clause)
  (cond (predicate then-clause)
        (else else-clause)))

(define (sqrt-iter guess x)
  (new-if (good-enough? guess x)
          guess
          (sqrt-iter (improve guess x)
 x)))
@mohanrajendran
mohanrajendran / Exercise1-7.md
Last active August 29, 2015 14:03
SICP Exercise 1.7

The good-enough? function is not so effective when we use small numbers as arguments in the function.

For example, when we want to find the square root of 0.0001 which is 0.01,

(sqrt 0.0001)

;.03230844833048122
@mohanrajendran
mohanrajendran / Exercise1-8.scm
Created July 9, 2014 12:41
SICP Exercise 1.8
(define (cbrt-iter guess prev-guess x)
(if (good-enough? guess prev-guess)
guess
(sqrt-iter (improve guess x)
guess
x)))
; cbrt-iter
(define (improve guess x)
(/ (+ (/ x (square guess)) (* 2 guess)) 3))
@mohanrajendran
mohanrajendran / Exercise1-9.md
Created July 11, 2014 00:28
SICP Exercise 1.9

Expansion of (+ 4 5) using first definition

(define (+ a b)
  (if (= a 0)
      b
      (inc (+ (dec a) b))))

(+ 4 5)
(inc (+ (dec 4) 5))
@mohanrajendran
mohanrajendran / Exercise1-10.md
Created July 13, 2014 21:56
SICP Exercise 1.10

The following are the results from defining and evaluating the Ackermann's function on various arguments.

(define (A x y)
  (cond ((= y 0) 0)
  	((= x 0) (* 2 y))
	((= y 1) 2)
	(else (A (- x 1)
	      	 (A x (- y 1))))))
; A