How do I translate the loop part of Common Lisp code into Clojure? ... functional orientation -
how translate loop part of working common lisp (sbcl v.1.2.3) code clojure (v.1.6)? bit frustrated after working on hours/days without results. somewhere don't functional orientation suppose ...
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; unconditional entropy ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; probabilities (setq list_occur_prob '()) ;; init ;; set probabilities want calculate entropy (setq list_occur_prob '(1/2 1/3 1/6)) ;; ;; function calculate unconditional ;; entropy h = -sigma i=0,n (pi*log2(pi) ;; bits persymbol. (setq entropy 0) ;; init (setq entropy (loop in list_occur_prob y = (* (log_base2 i) i) collect y )) (setq entropy (* -1 (apply '+ entropy))) ;; change sign ;; print unconditional entropy in bits per symbol. (print entropy) ;; btw, here entropy 1.4591479 bits per symbol.
they key operation need map
transforms sequence using function. in entropy example gave, following should work:
(def probabilities [1/2 1/3 1/6]) (defn log [base x] (/ (math/log x) (math/log base))) (defn entropy [probabilities] (->> probabilities (map #(* (log 2 %) %)) ; note - #(f %) shorthand (fn [x] (f x)) (reduce +) (-))) (entropy probabilities) ; => 1.459
when working collections, pipeline operator (->>
) used show sequence of operations. find easier read nested bracket syntax, if there lots of operations.
here, we're first mapping pi * log2(pi)
function on sequence, , summing using (reduce +)
Comments
Post a Comment