Thursday, December 26, 2019

SICP in Clojure: Chapter 1, Exercise 31

This is my Clojure solution to Chapter 1, Exercise 31:

(ns sicp.ch1.ex31)

(defn product
  [term a succ b]
  (if (> a b)
    1
    (* (term a)
       (product term (succ a) succ b))))

(defn factorial
  [n]
  (product identity 1 inc n))

(defn pi-approx
  [n]
  (* (product #(if (odd? %)
                 (/ (inc %) (+ 2 %))
                 (/ (+ 2 %) (inc %)))
              1
              inc
              n)
     4))

(defn product-iter
  [term a succ b]
  (letfn [(product-iter-step
            [a result]
            (if (> a b)
              result
              (product-iter-step (succ a) (* result (term a)))))]
    (product-iter-step a 1)))

(factorial 5) ; => 120

(double (pi-approx 1000)) ; => 3.143160705532266

(= (product identity 1 inc 10)
   (product-iter identity 1 inc 10)) ; => true

Wednesday, December 18, 2019

SICP in Clojure: Chapter 1, Exercise 30

This is my Clojure solution to Chapter 1, Exercise 30:

(ns sicp.ch1.ex30)

(defn sum-iter
  [term a succ b]
  (letfn [(sum-iter-step
            [a result]
            (if (> a b)
              result
              (sum-iter-step (succ a) (+ result (term a)))))]
    (sum-iter-step a 0)))

(sum-iter identity 0 inc 10) ; => 55

Monday, December 09, 2019

SICP in Clojure: Chapter 1, Exercise 29

This is my Clojure solution to Chapter 1, Exercise 29:

(ns sicp.ch1.ex29
  (:require [sicp.ch1.ex15 :as ch1-ex15]))

(defn sum
  [term a succ b]
  (if (> a b)
    0
    (+ (term a)
       (sum term (succ a) succ b))))

(defn integral
  [f a b dx]
  (* (sum f (+ a (/ dx 2.0)) (partial + dx) b)
     dx))

(defn integral-simpson
  [f a b n]
  (let [h (/ (- b a) n)]
    (* (sum #(let [m (cond
                       (zero? %) 1
                       (= n %)   1
                       (even? %) 2
                       (odd? %)  4)]
               (* m (f (+ a (* % h)))))
            0
            inc
            n)
       (/ h 3))))

(integral ch1-ex15/cube 0 1 0.01) ; => 0.24998750000000042

(integral ch1-ex15/cube 0 1 0.001) ; => 0.249999875000001

(double (integral-simpson ch1-ex15/cube 0 1 100)) ; => 0.25

(double (integral-simpson ch1-ex15/cube 0 1 1000)) ; => 0.25