Arantium Maestum

プログラミング、囲碁、読書の話題

2016-06-03から1日間の記事一覧

SICPの勉強 問題1.38~39

SICP1.3.3の問題1.38と1.39を解いてみる。 1.38問はネイピア数から2引いた数を近似するもの。 1, 2, 1, 1, 4, 1, 1, 6, 1, 1, 8, ...というめんどくさい数列をdの関数としてcont-fracに入れる。 (defn d [x] (if (= 2 (rem x 3)) (* 2 (inc (quot x 3))) 1)…

SICPの勉強 問題1.37

SICP1.3.3の問題1.37を解いてみる。 recursive process: (defn cont-frac [n d k] (letfn [(rec [i] (if (= i k) (/ (n i) (d i)) (/ (n i) (+ (d i) (rec (inc i))))))] (rec 1))) iterative process: (defn cont-frac [n d k] (loop [i k result 0] (if (z…

SICPの勉強 問題1.36

SICP1.3.3の問題1.36を解いてみる。 と、その前にまずfixed-pointをClojureっぽく書いてみる。 シーケンス[a0 a1 ... an-1 an]から[a0 a1 ... ai-2 ai-1] [a1 a2 ... ai-1 ai] [a2 a3 ... ai ai+1]と続くベクトルのシーケンスを作成する関数: (defn conseq …

SICPの勉強 問題1.33

SICP1.3.1の問題1.33を解いてみる。 filtered-accumulateのiterative process版: (defn filtered-accumulate [combiner null-value filt f a next b] (loop [a a result null-value] (cond (> a b) result (filt a) (recur (next a) (combiner (f a) result…

SICPの勉強 問題1.32

SICP1.3.1の問題1.32を解いてみる。 accumulateのrecursive process版: (defn accumulate [combiner null-value f a next b] (if (> a b) null-value (combiner (f a) (accumulate combiner null-value f (next a) next b)))) iterative process版: (defn …

SICPの勉強 問題1.31

SICP1.3.1の問題1.31を解いてみる。 productのrecursive process版: (defn product [f a next b] (if (> a b) 1 (* (f a) (product f (next a) next b)))) iterative process版: (defn product [f a next b] (loop [a a result 1] (if (> a b) result (rec…

SICPの勉強 問題1.30

SICP1.3.1の問題1.30を解いてみる。 末尾再帰にするのがポイント。問いの中のコードをできるだけ利用するなら: (defn sum [f a next b] (letfn [(iter [a result] (if (> a b) result (recur (next a) (+ (f a) result))))] (iter a 0))) これで先ほどの(in…

SICPの勉強 問題1.29

SICP1.3.1の問題1.29を解いてみる。 とりあえずSimpson Ruleを使わない積分法: (defn sum [f a next b] (if (> a b) 0 (+ (f a) (sum f (next a) next b)))) (defn integral [f a b dx] (letfn [(add-dx [x] (+ x dx))] (* (sum f (+ a (/ dx 2.0)) add-dx …

SICPの勉強 問題1.17~18

SICP1.2.4の問題1.17と1.18を解いてみる。 とりあえずdoubleとhalveを定義: (defn double [x] (* 2 x)) (defn halve [x] (/ x 2)) linear recursiveに書くとこんな感じ: (defn mul [a b] (cond (zero? b) 0 (even? b) (double (mul a (halve b))) :else (+…

SICPの勉強 問題1.16

SICP1.2.4の問題1.16を解いてみる。 (defn fast-exp-iter [b n] (loop [n n x 1 y b z 1] (cond (zero? n) z (< n (* 2 x)) (recur (- n x) 1 b (* y z)) :else (recur n (* 2 x) (* y y) z)))) 引数名が考えつかなかった、というのはいつもの弁。 n = 2a1 +…