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

No comments: