Skip to content

Commit

Permalink
added some of chatper 2, section 1
Browse files Browse the repository at this point in the history
  • Loading branch information
Robert Campbell committed Feb 5, 2012
1 parent b6f33ef commit d3c4e11
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 5 deletions.
21 changes: 16 additions & 5 deletions src/sicp/chapter1/section2.clj
Original file line number Diff line number Diff line change
Expand Up @@ -102,12 +102,23 @@


;; Exercise 1.16
;; Herwig's implementation

(letfn [(square [x] (* x x))]
(defn fast-expt' [b n]
(loop [n n a 1]
(loop [a 1 b b n n]
(cond (zero? n) a
(even? n) (recur (/ n 2)
(* b (square a)))
:else (recur (dec n)
(* b a))))))
(even? n) (recur a
(square b)
(/ n 2))
:else (recur (* a b)
b
(dec n))))))

;; Exercise 1.17

(letfn [(double [x] (* x 2))
(halve [x] (/ x 2))]
(defn multi [a b]
(cond (zero? b) a
)))
71 changes: 71 additions & 0 deletions src/sicp/chapter2/section1.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
(ns chatper2.section1
(:refer-clojure :exclude (cons))
(:use clojure.test))

;; Exercise 2.1

(defn gcd [a b]
(if (zero? b)
a
(gcd b (rem a b))))

(defn make-rat [n d]
(let [g (gcd n d)
n (/ n g)
d (/ d g)]
(if (and (pos? n) (neg? d))
[(* n -1) (* d -1)]
[n d])))


;; Exercise 2.2

(def make-segment vector)

(def start-segment first)

(def end-segment second)

(def make-point vector)

(def x-point first)

(def y-point second)

(defn midpoint-segment [[[x1 y1] [x2 y2]]]
[(/ (+ x1 x2) 2)
(/ (+ y1 y2) 2)])


;; Exercise 2.3

(def make-rect vector)

(letfn [(width [[[x1 _] [x2 _]]]
(Math/abs (- x1 x2)))
(height [[[_ y1] [_ y2]]]
(Math/abs (- y1 y2)))]

(defn rect-perimeter [hypotenuse]
(* 2 (+ (width hypotenuse)
(height hypotenuse))))

(defn rect-area [hypotenuse]
(* (width hypotenuse)
(height hypotenuse))))


;; Exercise 2.4

(defn cons [x y]
(fn [m]
(m x y)))

(defn car [z]
(z (fn [p _]
p)))

(defn cdr [z]
(z (fn [_ q]
q)))

0 comments on commit d3c4e11

Please sign in to comment.