Last active
September 26, 2015 14:30
-
-
Save p-baleine/0766be8a12af05929c17 to your computer and use it in GitHub Desktop.
Minimal line algebra functions in Clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(require '[clojure.core.match :refer [match]]) | |
;; (add [[7 3] [-1 2]] [[4 2] [3 -1]]) ;; => [[11 5] [[2 1]]] | |
(defn add [lhs rhs] | |
(match [lhs rhs] | |
[(l :guard number?) (r :guard number?)] (+ lhs rhs) | |
[(l :guard vector?) (r :guard vector?)] (vec (map add lhs rhs)))) | |
;; (transpose [[5 2] [6 3] [-2 0]]) ;; => [[5 6 -2] [2 3 0]] | |
(defn transpose [x] | |
(-> (partial map vector) (apply x) vec)) | |
;; (product [[1 2 -3] [2 7 1]] [[5 2] [6 3] [-2 0]]) ;; => [[23 8] [50 25]] | |
(defn product [lhs rhs] | |
(vec (for [x lhs] | |
(vec (for [y (transpose rhs)] | |
(reduce + (map * x y))))))) | |
;; (mul 3 [[11 5] [2 1]]) ;;=> [[33 15] [6 3]] | |
(defn mul [scalar x] | |
(match [x] | |
[(l :guard number?)] (* scalar l) | |
[(l :guard vector?)] (vec (map #(mul scalar %1) l)))) | |
;; (mean [10, 13, 8, 15, 8]) => 10.5 | |
(defn mean [x] | |
(float (/ (reduce + x) (count x)))) | |
;; (variance [10, 13, 8, 15, 8]) => 7.76 | |
(defn variance [x] | |
(let [m (mean x)] | |
(mean (map #(Math/pow (- %1 m) 2) x)))) | |
;; (standard-deviation [10, 13, 8, 15, 8]) => 2.785 | |
(defn standard-deviation [x] | |
(Math/sqrt (variance x))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment