Sunday, December 27, 2020

SICP in Clojure: Chapter 1, Exercise 44

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

(ns sicp.ch1.ex44
  (:require [sicp.ch1.ex16 :as ch1-ex16]
            [sicp.ch1.ex40 :as ch1-ex40]
            [sicp.ch1.ex43 :as ch1-ex43]))

(defn smooth
  [f]
  #(/ (+ (f (- % ch1-ex40/dx))
         (f %)
         (f (+ % ch1-ex40/dx)))
      3))

(defn n-fold-smooth
  [f n]
  ((ch1-ex43/repeated smooth n) f))

(comment
  ((smooth ch1-ex16/square) 5) ; => ~25

  ((n-fold-smooth ch1-ex16/square 2) 5) ; => ~25
  #__)

 

SICP in Clojure: Chapter 1, Exercise 43

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

(ns sicp.ch1.ex43
  (:require [sicp.ch1.ex16 :as ch1-ex16]
            [sicp.ch1.ex42 :as ch1-ex42]))

(defn repeated
  [f n]
  (loop [g identity n n]
    (if (zero? n)
      g
      (recur (ch1-ex42/compose f g) (dec n)))))

(comment
  ((repeated ch1-ex16/square 2) 5) ; => 625
  #__)

 

Wednesday, December 23, 2020

SICP in Clojure: Chapter 1, Exercise 42

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

(ns sicp.ch1.ex42
  (:require [sicp.ch1.ex16 :as ch1-ex16]))

(defn compose
  [f g]
  #(f (g %))) ; could use comp

(comment
  ((compose ch1-ex16/square inc) 6)
  #__)

 

SICP in Clojure: Chapter 1, Exercise 41

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

(ns sicp.ch1.ex41)

(defn double-it
  [f]
  #(f (f %))) ; could use comp

(comment
  (((double-it (double-it double-it)) inc) 5) ; => 21
  #__)