Learning/SICP/exercise_1_31.janet
2025-05-29 22:00:25 +02:00

47 lines
906 B
Plaintext

(defn product-iter [term next a b]
(defn iter [a result]
(if (> a b)
result
(iter (next a) (* result (term a)))))
(iter a 1))
(defn product-recur [term next a b]
(if (> a b)
1
(* (term a)
(product-recur term next (next a) b))))
(defn identity [n] n)
(defn inc [n] (+ n 1))
(defn factorial-iter [a b]
(product-iter identity inc a b))
(defn factorial-recur [a b]
(product-recur identity inc a b))
(defn pi [n]
(defn next [k]
(+ k 1))
(defn even-term [k]
(cond
(= (mod k 2) 0) (+ 2 k)
(+ 2 (- k 1))))
(defn odd-term [k]
(cond
(= (mod k 2) 0) (+ 3 k)
(+ 3 (- k 1))))
(* 4
(/
(product-iter even-term next 1 n)
(product-iter odd-term next 0 (- n 1)))))
(var x 1)
(while (< x 20)
(print (factorial-iter 1 x))
(print (factorial-recur 1 x))
(print "")
(print (pi x))
(print "")
(set x (+ x 1)))