Skip to content

Instantly share code, notes, and snippets.

@kaz-yos
Created March 13, 2015 17:09
Show Gist options
  • Save kaz-yos/2b088ea3a79c88af02e9 to your computer and use it in GitHub Desktop.
Save kaz-yos/2b088ea3a79c88af02e9 to your computer and use it in GitHub Desktop.
Pi Day
;;; pi calculation in Clojure
(defn square
"Square a number"
[n]
(* n n))
(defn seq-of-numerators
"Sequence of numerators up to n-th element"
[n]
(cond
(<= n 1) (seq [4])
:else (cons 4 (map square (range 1 n)))))
;; (seq-of-numerators 10)
;; => (4 1 4 9 16 25 36 49 64 81)
(defn seq-of-denominators
"Sequence of denominators up to n-th element"
[n]
(cond
(<= n 1) (seq [1])
:else (take n (filter odd? (range)))))
;; (seq-of-denominators 10)
;; => (1 3 5 7 9 11 13 15 17 19)
(defn numer-denom-pairs
"Pair of corresponding elements of numerator seq and denominator seq"
[n]
(map vector
(seq-of-numerators n)
(seq-of-denominators n)))
;; (numer-denom-pairs 10)
;; => ([4 1] [1 3] [4 5] [9 7] [16 9] [25 11] [36 13] [49 15] [64 17] [81 19])
(defn foldr
"Fold-right function"
([f init a-seq]
(if (empty? a-seq)
init
(f (first a-seq)
(foldr f init (rest a-seq))))))
;; (foldr + 0 [1 2 3 4])
;; => 10
(defn add-and-devide
"Given a vector of two and acculumator, perform addition and division
Result is a / (b+acc)"
[[a b] acc]
(/ a (+ b acc)))
;; (add-and-devide [4 5] 9/7)
;; => 7/11
(defn pi-calc
"More succinct pi calculator using foldr"
[n]
(foldr add-and-devide 0 (numer-denom-pairs n)))
;; (map (comp double pi-calc) [1 10 21 22 100 1000])
;; => (4.0 3.14159254044654 3.141592653589794 3.141592653589793 3.141592653589793 3.141592653589793)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment