Tuesday, July 28, 2020

SICP in Clojure: Chapter 1, Exercise 37

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

(ns sicp.ch1.ex37
  (:require [sicp.ch1.ex32 :as ch1-ex32]))

(def n (constantly 1))

(def d (constantly 1))

(defn cont-frac
  [n d k]
  (ch1-ex32/accumulate #(/ (n %1) (+ (d %1) %2))
                       0
                       identity
                       1
                       inc
                       k))

(defn cont-frac-iter
  [n d k]
  (ch1-ex32/accumulate-iter #(/ (n %1) (+ (d %1) %2))
                            0
                            identity
                            1
                            inc
                            k))

(double (/ 1
           (cont-frac (constantly 1)
                      (constantly 1)
                      12))) ; => 1.618055555555556 - accurate to 4
                                        ; decimal places

(double (/ 1 (cont-frac-iter (constantly 1)
                             (constantly 1)
                             12))) ; => 1.618055555555556