Last active
December 29, 2015 16:49
-
-
Save graue/7699851 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
(ns vectors | |
(:require [clojure.test :refer [deftest is run-tests]])) | |
(defprotocol VectorMath2D | |
(-vplus [v1 v2] "Adds two vectors")) | |
(defrecord Vec2D [x y] | |
VectorMath2D | |
(-vplus [v1 v2] | |
(Vec2D. (+ (:x v1) | |
(get v2 :x 0)) | |
(+ (:y v1) | |
(get v2 :y 0))))) | |
(defn v+ | |
"A more general function to add 2D vectors. Takes any number of arguments, | |
like +." | |
([] (Vec2D. 0 0)) | |
([v] v) | |
([v1 v2] (-vplus v1 v2)) | |
([v1 v2 & more] (reduce -vplus (-vplus v1 v2) more))) | |
(deftest addition | |
(let [a (Vec2D. 3 0) | |
b (Vec2D. -1 -1) | |
c (Vec2D. 2 5)] | |
(is (= (Vec2D. 0 0) (v+))) | |
(is (= (Vec2D. 3 0) (v+ a))) | |
(is (= (Vec2D. 2 -1) (v+ a b))) | |
(is (= (Vec2D. 4 4) (v+ a b c))))) | |
(comment | |
(run-tests) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment