├── .gitignore ├── LICENSE ├── README.md ├── pom.xml ├── project.clj └── src └── symbolic_algebra └── core.clj /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /classes 3 | /checkouts 4 | pom.xml.asc 5 | *.jar 6 | *.class 7 | /.lein-* 8 | /.nrepl-port 9 | .hgignore 10 | .hg/ 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC 2 | LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM 3 | CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 4 | 5 | 1. DEFINITIONS 6 | 7 | "Contribution" means: 8 | 9 | a) in the case of the initial Contributor, the initial code and 10 | documentation distributed under this Agreement, and 11 | 12 | b) in the case of each subsequent Contributor: 13 | 14 | i) changes to the Program, and 15 | 16 | ii) additions to the Program; 17 | 18 | where such changes and/or additions to the Program originate from and are 19 | distributed by that particular Contributor. A Contribution 'originates' from 20 | a Contributor if it was added to the Program by such Contributor itself or 21 | anyone acting on such Contributor's behalf. Contributions do not include 22 | additions to the Program which: (i) are separate modules of software 23 | distributed in conjunction with the Program under their own license 24 | agreement, and (ii) are not derivative works of the Program. 25 | 26 | "Contributor" means any person or entity that distributes the Program. 27 | 28 | "Licensed Patents" mean patent claims licensable by a Contributor which are 29 | necessarily infringed by the use or sale of its Contribution alone or when 30 | combined with the Program. 31 | 32 | "Program" means the Contributions distributed in accordance with this 33 | Agreement. 34 | 35 | "Recipient" means anyone who receives the Program under this Agreement, 36 | including all Contributors. 37 | 38 | 2. GRANT OF RIGHTS 39 | 40 | a) Subject to the terms of this Agreement, each Contributor hereby grants 41 | Recipient a non-exclusive, worldwide, royalty-free copyright license to 42 | reproduce, prepare derivative works of, publicly display, publicly perform, 43 | distribute and sublicense the Contribution of such Contributor, if any, and 44 | such derivative works, in source code and object code form. 45 | 46 | b) Subject to the terms of this Agreement, each Contributor hereby grants 47 | Recipient a non-exclusive, worldwide, royalty-free patent license under 48 | Licensed Patents to make, use, sell, offer to sell, import and otherwise 49 | transfer the Contribution of such Contributor, if any, in source code and 50 | object code form. This patent license shall apply to the combination of the 51 | Contribution and the Program if, at the time the Contribution is added by the 52 | Contributor, such addition of the Contribution causes such combination to be 53 | covered by the Licensed Patents. The patent license shall not apply to any 54 | other combinations which include the Contribution. No hardware per se is 55 | licensed hereunder. 56 | 57 | c) Recipient understands that although each Contributor grants the licenses 58 | to its Contributions set forth herein, no assurances are provided by any 59 | Contributor that the Program does not infringe the patent or other 60 | intellectual property rights of any other entity. Each Contributor disclaims 61 | any liability to Recipient for claims brought by any other entity based on 62 | infringement of intellectual property rights or otherwise. As a condition to 63 | exercising the rights and licenses granted hereunder, each Recipient hereby 64 | assumes sole responsibility to secure any other intellectual property rights 65 | needed, if any. For example, if a third party patent license is required to 66 | allow Recipient to distribute the Program, it is Recipient's responsibility 67 | to acquire that license before distributing the Program. 68 | 69 | d) Each Contributor represents that to its knowledge it has sufficient 70 | copyright rights in its Contribution, if any, to grant the copyright license 71 | set forth in this Agreement. 72 | 73 | 3. REQUIREMENTS 74 | 75 | A Contributor may choose to distribute the Program in object code form under 76 | its own license agreement, provided that: 77 | 78 | a) it complies with the terms and conditions of this Agreement; and 79 | 80 | b) its license agreement: 81 | 82 | i) effectively disclaims on behalf of all Contributors all warranties and 83 | conditions, express and implied, including warranties or conditions of title 84 | and non-infringement, and implied warranties or conditions of merchantability 85 | and fitness for a particular purpose; 86 | 87 | ii) effectively excludes on behalf of all Contributors all liability for 88 | damages, including direct, indirect, special, incidental and consequential 89 | damages, such as lost profits; 90 | 91 | iii) states that any provisions which differ from this Agreement are offered 92 | by that Contributor alone and not by any other party; and 93 | 94 | iv) states that source code for the Program is available from such 95 | Contributor, and informs licensees how to obtain it in a reasonable manner on 96 | or through a medium customarily used for software exchange. 97 | 98 | When the Program is made available in source code form: 99 | 100 | a) it must be made available under this Agreement; and 101 | 102 | b) a copy of this Agreement must be included with each copy of the Program. 103 | 104 | Contributors may not remove or alter any copyright notices contained within 105 | the Program. 106 | 107 | Each Contributor must identify itself as the originator of its Contribution, 108 | if any, in a manner that reasonably allows subsequent Recipients to identify 109 | the originator of the Contribution. 110 | 111 | 4. COMMERCIAL DISTRIBUTION 112 | 113 | Commercial distributors of software may accept certain responsibilities with 114 | respect to end users, business partners and the like. While this license is 115 | intended to facilitate the commercial use of the Program, the Contributor who 116 | includes the Program in a commercial product offering should do so in a 117 | manner which does not create potential liability for other Contributors. 118 | Therefore, if a Contributor includes the Program in a commercial product 119 | offering, such Contributor ("Commercial Contributor") hereby agrees to defend 120 | and indemnify every other Contributor ("Indemnified Contributor") against any 121 | losses, damages and costs (collectively "Losses") arising from claims, 122 | lawsuits and other legal actions brought by a third party against the 123 | Indemnified Contributor to the extent caused by the acts or omissions of such 124 | Commercial Contributor in connection with its distribution of the Program in 125 | a commercial product offering. The obligations in this section do not apply 126 | to any claims or Losses relating to any actual or alleged intellectual 127 | property infringement. In order to qualify, an Indemnified Contributor must: 128 | a) promptly notify the Commercial Contributor in writing of such claim, and 129 | b) allow the Commercial Contributor tocontrol, and cooperate with the 130 | Commercial Contributor in, the defense and any related settlement 131 | negotiations. The Indemnified Contributor may participate in any such claim 132 | at its own expense. 133 | 134 | For example, a Contributor might include the Program in a commercial product 135 | offering, Product X. That Contributor is then a Commercial Contributor. If 136 | that Commercial Contributor then makes performance claims, or offers 137 | warranties related to Product X, those performance claims and warranties are 138 | such Commercial Contributor's responsibility alone. Under this section, the 139 | Commercial Contributor would have to defend claims against the other 140 | Contributors related to those performance claims and warranties, and if a 141 | court requires any other Contributor to pay any damages as a result, the 142 | Commercial Contributor must pay those damages. 143 | 144 | 5. NO WARRANTY 145 | 146 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON 147 | AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER 148 | EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR 149 | CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A 150 | PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the 151 | appropriateness of using and distributing the Program and assumes all risks 152 | associated with its exercise of rights under this Agreement , including but 153 | not limited to the risks and costs of program errors, compliance with 154 | applicable laws, damage to or loss of data, programs or equipment, and 155 | unavailability or interruption of operations. 156 | 157 | 6. DISCLAIMER OF LIABILITY 158 | 159 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY 160 | CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, 161 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION 162 | LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 163 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 164 | ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE 165 | EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY 166 | OF SUCH DAMAGES. 167 | 168 | 7. GENERAL 169 | 170 | If any provision of this Agreement is invalid or unenforceable under 171 | applicable law, it shall not affect the validity or enforceability of the 172 | remainder of the terms of this Agreement, and without further action by the 173 | parties hereto, such provision shall be reformed to the minimum extent 174 | necessary to make such provision valid and enforceable. 175 | 176 | If Recipient institutes patent litigation against any entity (including a 177 | cross-claim or counterclaim in a lawsuit) alleging that the Program itself 178 | (excluding combinations of the Program with other software or hardware) 179 | infringes such Recipient's patent(s), then such Recipient's rights granted 180 | under Section 2(b) shall terminate as of the date such litigation is filed. 181 | 182 | All Recipient's rights under this Agreement shall terminate if it fails to 183 | comply with any of the material terms or conditions of this Agreement and 184 | does not cure such failure in a reasonable period of time after becoming 185 | aware of such noncompliance. If all Recipient's rights under this Agreement 186 | terminate, Recipient agrees to cease use and distribution of the Program as 187 | soon as reasonably practicable. However, Recipient's obligations under this 188 | Agreement and any licenses granted by Recipient relating to the Program shall 189 | continue and survive. 190 | 191 | Everyone is permitted to copy and distribute copies of this Agreement, but in 192 | order to avoid inconsistency the Agreement is copyrighted and may only be 193 | modified in the following manner. The Agreement Steward reserves the right to 194 | publish new versions (including revisions) of this Agreement from time to 195 | time. No one other than the Agreement Steward has the right to modify this 196 | Agreement. The Eclipse Foundation is the initial Agreement Steward. The 197 | Eclipse Foundation may assign the responsibility to serve as the Agreement 198 | Steward to a suitable separate entity. Each new version of the Agreement will 199 | be given a distinguishing version number. The Program (including 200 | Contributions) may always be distributed subject to the version of the 201 | Agreement under which it was received. In addition, after a new version of 202 | the Agreement is published, Contributor may elect to distribute the Program 203 | (including its Contributions) under the new version. Except as expressly 204 | stated in Sections 2(a) and 2(b) above, Recipient receives no rights or 205 | licenses to the intellectual property of any Contributor under this 206 | Agreement, whether expressly, by implication, estoppel or otherwise. All 207 | rights in the Program not expressly granted under this Agreement are 208 | reserved. 209 | 210 | This Agreement is governed by the laws of the State of New York and the 211 | intellectual property laws of the United States of America. No party to this 212 | Agreement will bring a legal action under this Agreement more than one year 213 | after the cause of action arose. Each party waives its rights to a jury trial 214 | in any resulting litigation. 215 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Symbolic Algebra 2 | 3 | A library for performing algebraic operations across multiple numeric types, inspired by the exercise presented in [Structure and Interpretation of Computer Programs](https://mitpress.mit.edu/sicp/) as well as [Richard Zippel’s Weyl package for Common Lisp](http://www.cs.cornell.edu/rz/computer-algebra.html). 4 | 5 | Currently this implements **rationals**, **complex numbers**, and univariate **polynomials** as well as any combination thereof. Clojure's protocols are used for single dispatch along with functions for type coercion. The base type extends the java.lang.Number abstract class in order to support all JVM numeric types, everything from shorts to doubles to BigIntegers. Finally, reader macros are used for legibility. 6 | 7 | The latest update uses [Stein's Algorithm (Binary GCD)](https://en.wikipedia.org/wiki/Binary_GCD_algorithm) instead of Euclid's to factor rationals, adds functions to convert between polynomials with dense and sparse term lists, and comes with a suite of generative tests written using the new [clojure.spec](http://clojure.org/about/spec) library—and therefore now requires Clojure 1.9.0-alpha14. 8 | 9 | ## Usage: 10 | 11 | ``` 12 | ;; 5+1/2i + 2+1/4i = 7+3/4i 13 | => (add (Complex. 5 (Rational. 1 2)) (Complex. 2 (Rational. 1 4))) 14 | => 10+3/4i 15 | ``` 16 | ``` 17 | ;; 1/2 - 1/3 = 1/6 18 | => (sub (Rational. 1 2) (Rational. 1 3)) 19 | => 1/6 20 | ``` 21 | ``` 22 | ;; 5+2i * 1+1i = 3+7i 23 | => (mul (Complex. 5 2) (Complex. 1 1)) 24 | => 3+7i 25 | ``` 26 | ``` 27 | ;; (x^5 + 3)/(x^5 + 3) = 1 28 | => (div (Poly. 'x '((5 1) (0 3))) (Poly. 'x '((5 1) (0 3)))) 29 | => x:((0 1)) 30 | ``` 31 | ``` 32 | ;; 3/9 == 9/27 33 | => (equal? (Rational. 3 9) (Rational. 9 27)) 34 | => true 35 | ``` 36 | ``` 37 | ;;polynomials must be in sparse form to operate on 38 | ;; y^5 + 2y^4 + 3y^2 - 2y - 5 39 | => (dense-to-sparse (Poly. 'y '(1 2 0 3 -2 -5))) 40 | => y:((5 1) (4 2) (2 3) (1 -2) (0 -5)) 41 | => (sparse-to-dense (Poly. 'y '((5 1) (4 2) (2 3) (1 -2) (0 -5)))) 42 | => y:(1 2 0 3 -2 -5) 43 | ``` 44 | 45 | ## Known Issues and Future Features 46 | 47 | Subtyping is still not perfect (thanks core.spec!) as it requires extending GCD over a Euclidean domain in order to factor rationals and polynomials. In addition, the next version will allow multivariate polynomials for use with my [Power Series](https://github.com/Sophia-Gold/power-series.clj) package. -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | symbolic-algebra 4 | symbolic-algebra 5 | jar 6 | 0.5.1 7 | symbolic-algebra 8 | symbolic algebra library with numerical tower 9 | 10 | 11 | Eclipse Public License 12 | http://www.eclipse.org/legal/epl-v10.html 13 | 14 | 15 | 16 | 12fb3807253a616e9b01c7dca5dc564cd32bf0c2 17 | 18 | 19 | 20 | 21 | src 22 | test 23 | 24 | 25 | resources 26 | 27 | 28 | 29 | 30 | resources 31 | 32 | 33 | target 34 | target/classes 35 | 36 | 37 | 38 | 39 | central 40 | https://repo1.maven.org/maven2/ 41 | 42 | false 43 | 44 | 45 | true 46 | 47 | 48 | 49 | clojars 50 | https://clojars.org/repo/ 51 | 52 | true 53 | 54 | 55 | true 56 | 57 | 58 | 59 | 60 | 61 | org.clojure 62 | clojure 63 | 1.9.0 64 | 65 | 66 | org.clojure 67 | test.check 68 | 0.9.0 69 | 70 | 71 | org.clojure 72 | test.generative 73 | 0.5.2 74 | 75 | 76 | org.clojure 77 | spec.alpha 78 | 0.1.143 79 | 80 | 81 | org.clojure 82 | core.specs.alpha 83 | 0.1.24 84 | 85 | 86 | 87 | 88 | 92 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject symbolic-algebra "0.5.1" 2 | :description "symbolic algebra library with numerical tower" 3 | :license {:name "Eclipse Public License" 4 | :url "http://www.eclipse.org/legal/epl-v10.html"} 5 | :dependencies [[org.clojure/clojure "1.9.0"] 6 | [org.clojure/test.check "0.9.0"] 7 | [org.clojure/test.generative "0.5.2"] 8 | [org.clojure/spec.alpha "0.1.143"] 9 | [org.clojure/core.specs.alpha "0.1.24"]] 10 | :main ^:skip-aot symbolic-algebra.core 11 | :target-path "target/%s" 12 | :profiles {:uberjar {:aot :all}}) 13 | -------------------------------------------------------------------------------- /src/symbolic_algebra/core.clj: -------------------------------------------------------------------------------- 1 | (ns symbolic-algebra.core 2 | (:gen-class) 3 | (:require [clojure.spec.alpha :as s] 4 | [clojure.spec.test.alpha :as stest] 5 | [clojure.spec.gen.alpha :as gen])) 6 | 7 | ;; (set! *warn-on-reflection* true) 8 | ;; (set! *unchecked-math* :warn-on-boxed) 9 | 10 | ;TYPES 11 | (defrecord Rational [^long numerator ^long denominator]) 12 | (defmethod print-method Rational [v ^java.io.Writer w] 13 | (print-method (:numerator v) w) 14 | (.write w "/") 15 | (print-method (:denominator v) w)) 16 | (defrecord Complex [^long real ^long imaginary]) 17 | (defmethod print-method Complex [v ^java.io.Writer w] 18 | (print-method (:real v) w) 19 | (.write w "+") 20 | (print-method (:imaginary v) w) 21 | (.write w "i")) 22 | (defrecord Poly [variable term-list]) 23 | (defmethod print-method Poly [v ^java.io.Writer w] 24 | (print-method (:variable v) w) 25 | (.write w ":") 26 | (print-method (:term-list v) w)) 27 | 28 | ;PROTOCOLS 29 | (defprotocol Algebra 30 | (add [a b]) 31 | (sub [a b]) 32 | (mul [a b]) 33 | (div [a b]) 34 | (equal? [a b])) 35 | 36 | ;Maths 37 | (defn round [n] 38 | (if (>= n 0.0) 39 | (Math/floor n) 40 | (Math/ceil n))) 41 | (defn square [x] 42 | (mul x x)) 43 | 44 | ;COMPLEX 45 | (defn real-part [rect] 46 | (get rect :real)) 47 | (defn imag-part [rect] 48 | (get rect :imaginary)) 49 | (defn magnitude [polar] 50 | (Math/sqrt (add (square (real-part polar)) 51 | (square (imag-part polar))))) 52 | (defn angle [polar] 53 | (Math/atan2 (imag-part polar) 54 | (real-part polar))) 55 | (defn make-from-real-imag [x y] 56 | (Complex. x y)) 57 | (defn make-from-mag-ang [r a] 58 | (Complex. (int (round (mul r (Math/cos a)))) 59 | (int (round (mul r (Math/sin a)))))) 60 | 61 | ;POLYNOMIALS 62 | (defn variable [p] 63 | (get p :variable)) 64 | (defn term-list [p] 65 | (get p :term-list)) 66 | (defn order [term] 67 | (first term)) 68 | (defn coeff [term] 69 | (fnext term)) 70 | (defn make-term [order coeff] 71 | (list order coeff)) 72 | (defn first-term [term-list] 73 | (first term-list)) 74 | (defn first-term-dense [term-list] 75 | (concat 76 | (first term-list) 77 | (- (count term-list) 1))) 78 | (defn rest-terms [term-list] 79 | (next term-list)) 80 | (defn adjoin-term [term term-list] 81 | (cons term term-list)) 82 | (defn adjoin-term-dense [term term-list] 83 | (if (zero? (coeff term)) 84 | term-list 85 | (cons (coeff term) term-list))) 86 | (defn sparse-to-dense [p] 87 | (let [poly (reverse (term-list p)) 88 | diff-terms (map #(vector (dec (- (first %1) (first %2))) (second %1)) 89 | (next poly) poly)] 90 | (->> diff-terms 91 | (cons (first poly)) 92 | (mapcat #(concat (repeat (first %) 0) [(second %)])) 93 | (reverse) 94 | (#(Poly. (variable p) %))))) 95 | (defn dense-to-sparse [p] 96 | (->> (term-list p) 97 | (reverse) 98 | (map-indexed #(if (not= %2 0) (list %1 %2))) 99 | (filter some?) 100 | (reverse) 101 | (#(Poly. (variable p) %)))) 102 | 103 | ;RATIONALS 104 | (defn numer [x] 105 | (get x :numerator)) 106 | (defn denom [x] 107 | (get x :denominator)) 108 | 109 | ;; (defn gcd [a b] 110 | ;; (if (zero? b) 111 | ;; a 112 | ;; (recur b (mod a b)))) 113 | (defn gcd [a b] 114 | (cond 115 | (zero? a) b 116 | (zero? b) a 117 | (neg? a) (- a) 118 | (neg? b) (- b) 119 | (and (even? a) (even? b)) (* 2 120 | (gcd (unsigned-bit-shift-right a 1) 121 | (unsigned-bit-shift-right b 1))) 122 | (and (even? a) (odd? b)) (recur (unsigned-bit-shift-right a 1) b) 123 | (and (odd? a) (even? b)) (recur a (unsigned-bit-shift-right b 1)) 124 | (and (odd? a) (odd? b)) (recur (unsigned-bit-shift-right 125 | (Math/abs (long (- a b))) ;; coerce to avoid reflection 126 | 1) (min a b)))) 127 | (defn extended-gcd [a b] 128 | (let [class-a (class a)] 129 | (cond 130 | (number? a) (gcd a b) 131 | (= class-a Rational) (reduce gcd (list (numer a) (denom a) (numer b) (denom b))) 132 | (= class-a Complex) (reduce gcd (list (real-part a) (imag-part a) (real-part b) (imag-part b))) 133 | (= class-a Poly) (reduce gcd (concat (term-list a) (term-list b)))))) 134 | 135 | (defn make-rat [n d] 136 | (let [g (extended-gcd n d)] 137 | (Rational. (div n g) (div d g)))) 138 | 139 | ;TYPE COERCION 140 | (defn raise-types [a b proc] 141 | (let [class-a (class a) 142 | class-b (class b)] 143 | (cond 144 | (and (number? a) (= class-b Rational)) (proc (Rational. a 1) b) 145 | (and (number? a) (= class-b Complex)) (proc (Complex. a 0) b) 146 | (and (number? a) (= class-b Poly)) (proc (Poly. (variable b) (list (list 0 a))) b) 147 | (and (= class-a Rational) (number? b)) (proc a (Rational. b 1)) 148 | (and (= class-a Rational) (= class-b Complex)) (proc (Complex. a 0) b) 149 | (and (= class-a Rational) (= class-b Poly)) (proc (Poly. (variable b) (list (list 0 a))) b) 150 | (and (= class-a Complex) (number? b)) (proc a (Complex. b 0)) 151 | (and (= class-a Complex) (= class-b Rational)) (proc a (Complex. b 0)) 152 | (and (= class-a Complex) (= class-b Poly)) (proc (Poly. (variable b) (list (list 0 a))) b) 153 | (and (= class-a Poly) (number? b)) (proc a (Poly. (variable a) (list (list 0 b)))) 154 | (and (= class-a Poly) (= class-b Rational)) (proc a (Poly. (variable a) (list (list 0 b)))) 155 | (and (= class-a Poly) (= class-b Complex)) (proc a (Poly. (variable a) (list (list 0 b))))))) 156 | 157 | (defn reduce-type [a] 158 | (let [class-a (class a)] 159 | (cond 160 | (and (= class-a Rational) 161 | (= (denom a) 1)) (numer a) 162 | (and (= class-a Complex) 163 | (= (imag-part a) 0)) (reduce-type (real-part a)) 164 | (and (= class-a Poly) 165 | (empty (rest-terms (term-list a))) 166 | (= (order (first-term (term-list a))) 0)) (reduce-type (coeff (first-term (term-list a)))) 167 | :else a))) 168 | 169 | (extend-type Number 170 | Algebra 171 | (add [a b] 172 | (if (= (class a) (class b)) 173 | (+ a b) 174 | (raise-types a b add))) 175 | (sub [a b] 176 | (if (= (class a) (class b)) 177 | (- a b) 178 | (raise-types a b sub))) 179 | (mul [a b] 180 | (if (= (class a) (class b)) 181 | (* a b) 182 | (raise-types a b mul))) 183 | (div [a b] 184 | (if (= (class a) (class b)) 185 | (/ a b) 186 | (raise-types a b div))) 187 | (equal? [a b] 188 | (if (= (class a) (class b)) 189 | (= a b) 190 | (raise-types a b equal?)))) 191 | 192 | (extend-type Rational 193 | Algebra 194 | (add [a b] 195 | (if (= (class a) (class b)) 196 | (reduce-type 197 | (make-rat (add (mul (numer a) (denom b)) 198 | (mul (numer b) (denom a))) 199 | (mul (denom a) (denom b)))) 200 | (raise-types a b add))) 201 | (sub [a b] 202 | (if (= (class a) (class b)) 203 | (reduce-type 204 | (make-rat (sub (mul (numer a) (denom b)) 205 | (mul (numer b) (denom a))) 206 | (mul (denom a) (denom b)))) 207 | (raise-types a b sub))) 208 | (mul [a b] 209 | (if (= (class a) (class b)) 210 | (reduce-type 211 | (make-rat (mul (numer a) (numer b)) 212 | (mul (denom a) (denom b)))) 213 | (raise-types a b mul))) 214 | (div [a b] 215 | (if (= (class a) (class b)) 216 | (reduce-type 217 | (make-rat (mul (numer a) (denom b)) 218 | (mul (denom a) (numer b)))) 219 | (raise-types a b div))) 220 | (equal? [a b] 221 | (if (= (class a) (class b)) 222 | (let [simple-a (make-rat (numer a) (denom a)) 223 | simple-b (make-rat (numer b) (denom b))] 224 | (if (and (equal? (numer simple-a) (numer simple-b)) 225 | (equal? (denom simple-a) (denom simple-b))) 226 | true 227 | false)) 228 | (raise-types a b equal?)))) 229 | 230 | (extend-type Complex 231 | Algebra 232 | (add [a b] 233 | (if (= (class a) (class b)) 234 | (reduce-type 235 | (make-from-real-imag (add (real-part a) (real-part b)) 236 | (add (imag-part a) (imag-part b)))) 237 | (raise-types a b add))) 238 | (sub [a b] 239 | (if (= (class a) (class b)) 240 | (reduce-type 241 | (make-from-real-imag (sub (real-part a) (real-part b)) 242 | (sub (imag-part a) (imag-part b)))) 243 | (raise-types a b sub))) 244 | (mul [a b] 245 | (if (= (class a) (class b)) 246 | (reduce-type 247 | (make-from-mag-ang (mul (magnitude a) (magnitude b)) 248 | (add (angle a) (angle b)))) 249 | (raise-types a b mul))) 250 | (div [a b] 251 | (if (= (class a) (class b)) 252 | (reduce-type 253 | (make-from-mag-ang (div (magnitude a) (magnitude b)) 254 | (sub (angle a) (angle b)))) 255 | (raise-types a b div))) 256 | (equal? [a b] 257 | (if (= (class a) (class b)) 258 | (if (and (equal? (real-part a) (real-part b)) 259 | (equal? (imag-part a) (imag-part b))) 260 | true 261 | false) 262 | (raise-types a b equal?)))) 263 | 264 | (defn negate-terms [termlist] 265 | (map 266 | (fn [t] 267 | (make-term (order t) 268 | (sub 0 (coeff t)))) 269 | termlist)) 270 | (defn add-terms [l1 l2] 271 | (cond 272 | (and (empty? l1) (empty? l2)) '() 273 | (empty? l1) l2 274 | (empty? l2) l1 275 | :else 276 | (let [t1 (first-term l1) 277 | t2 (first-term l2)] 278 | (cond 279 | (> (order t1) (order t2)) (adjoin-term t1 (add-terms (rest-terms l1) l2)) 280 | (< (order t1) (order t2)) (adjoin-term t2 (add-terms l1 (rest-terms l2))) 281 | :else 282 | (adjoin-term (make-term (order t1) 283 | (add (coeff t1) (coeff t2))) 284 | (add-terms (rest-terms l1) 285 | (rest-terms l2))))))) 286 | (defn mul-term-by-all-terms [t1 l] 287 | (if (empty? l) 288 | l 289 | (let [t2 (first-term l)] 290 | (adjoin-term 291 | (make-term (+ (order t1) (order t2)) 292 | (mul (coeff t1) (coeff t2))) 293 | (mul-term-by-all-terms t1 (rest-terms l)))))) 294 | (defn mul-terms [l1 l2] 295 | (if (empty? l1) 296 | l1 297 | (add-terms (mul-term-by-all-terms (first-term l1) l2) 298 | (mul-terms (rest-terms l1) l2)))) 299 | (defn div-terms [l1 l2] 300 | (if (empty? l1) 301 | l1 302 | (let [t1 (first-term l1) 303 | t2 (first-term l2)] 304 | (if (> (order t2) (order t1)) 305 | l1 306 | (let [new-c (div (coeff t1) (coeff t2)) 307 | new-o (- (order t1) (order t2))] 308 | (let [rest-of-result 309 | (div-terms 310 | (add-terms l1 311 | (negate-terms 312 | (mul-terms l2 313 | (list 314 | (make-term new-o new-c))))) 315 | l2)] 316 | (list (adjoin-term (make-term new-o new-c) 317 | (first rest-of-result)) 318 | (fnext rest-of-result)))))))) 319 | 320 | (extend-type Poly 321 | Algebra 322 | (add [a b] 323 | (if (= (class a) (class b)) 324 | (reduce-type 325 | (if (= (variable a) (variable b)) 326 | (Poly. (variable a) 327 | (add-terms (term-list a) 328 | (term-list b))) 329 | (println "ERROR: Polys not in same var -- ADD-POLY" 330 | (list a b)))) 331 | (raise-types a b add))) 332 | (sub [a b] 333 | (if (= (class a) (class b)) 334 | (reduce-type 335 | (if (= (variable a) (variable b)) 336 | (Poly. (variable a) 337 | (add-terms (term-list a) 338 | (negate-terms (term-list b)))) 339 | (println "ERROR: Polys not in same var -- SUB-POLY" 340 | (list a b)))) 341 | (raise-types a b sub))) 342 | (mul [a b] 343 | (if (= (class a) (class b)) 344 | (reduce-type 345 | (if (= (variable a) (variable b)) 346 | (Poly. (variable a) 347 | (mul-terms (term-list a) 348 | (term-list b))) 349 | (println "ERROR: Polys not in same var -- MUL-POLY" 350 | (list a b)))) 351 | (raise-types a b mul))) 352 | (div [a b] 353 | (if (= (class a) (class b)) 354 | (reduce-type 355 | (if (= (variable a) (variable b)) 356 | (let [result (div-terms (term-list a) 357 | (term-list b))] 358 | (Poly. (variable a) (first result))) 359 | (println "ERROR: Polys not in same var -- DIV-POLY" 360 | (list a b)))) 361 | (raise-types a b div))) 362 | (equal? [a b] 363 | (if (= (class a) (class b)) 364 | (reduce-type 365 | (let [sparse-a (dense-to-sparse a) 366 | sparse-b (dense-to-sparse b)] 367 | (if (= (variable sparse-a) (variable sparse-b)) 368 | (not-any? false? 369 | (map equal? (term-list sparse-a) (term-list sparse-b))) 370 | false))) 371 | (raise-types a b equal?)))) 372 | 373 | 374 | (defn -main [] 375 | ) 376 | 377 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; 378 | 379 | ;; TESTS 380 | 381 | (def non-zero-int 382 | (gen/such-that (complement zero?) 383 | (s/gen int?))) 384 | 385 | (s/def ::rational 386 | (s/with-gen #(instance? Rational %) 387 | (fn [] (gen/fmap #(->Rational (first %) (second %)) 388 | (gen/tuple 389 | non-zero-int 390 | non-zero-int))))) 391 | (s/def ::rational-rational 392 | (s/with-gen #(instance? Rational %) 393 | (fn [] (gen/fmap #(->Rational (first %) (second %)) 394 | (gen/tuple 395 | (s/gen ::rational) 396 | (s/gen ::rational)))))) 397 | (s/def ::rational-complex-numer 398 | (s/with-gen #(instance? Rational %) 399 | (fn [] (gen/fmap #(->Rational (first %) (second %)) 400 | (gen/tuple 401 | (s/gen ::complex) 402 | (s/gen int?)))))) 403 | (s/def ::rational-complex-denom 404 | (s/with-gen #(instance? Rational %) 405 | (fn [] (gen/fmap #(->Rational (first %) (second %)) 406 | (gen/tuple 407 | (s/gen int?) 408 | (s/gen ::complex)))))) 409 | (s/def ::rational-complex 410 | (s/with-gen #(instance? Rational %) 411 | (fn [] (gen/fmap #(->Rational (first %) (second %)) 412 | (gen/tuple 413 | (s/gen ::complex) 414 | (s/gen ::complex)))))) 415 | (s/def ::complex 416 | (s/with-gen #(instance? Complex %) 417 | (fn [] (gen/fmap #(->Complex (first %) (second %)) 418 | (gen/tuple 419 | (s/gen int?) 420 | (s/gen int?)))))) 421 | (s/def ::complex-rational-real 422 | (s/with-gen #(instance? Complex %) 423 | (fn [] (gen/fmap #(->Complex (first %) (second %)) 424 | (gen/tuple 425 | (s/gen ::rational) 426 | non-zero-int))))) 427 | (s/def ::complex-rational-imag 428 | (s/with-gen #(instance? Complex %) 429 | (fn [] (gen/fmap #(->Complex (first %) (second %)) 430 | (gen/tuple 431 | (s/gen int?) 432 | (s/gen ::rational)))))) 433 | (s/def ::complex-rational 434 | (s/with-gen #(instance? Complex %) 435 | (fn [] (gen/fmap #(->Complex (first %) (second %)) 436 | (gen/tuple 437 | (s/gen ::rational) 438 | (s/gen ::rational)))))) 439 | 440 | (s/def ::mono (s/or ;; :int int? 441 | :rational ::rational 442 | :rational-:rational ::rational-rational 443 | ;; :rational-complex-numer ::rational-complex-numer 444 | ;; :rational-complex-denom ::rational-complex-denom 445 | ;; :rational-complex ::rational-complex 446 | :complex ::complex 447 | ;; :complex-rational ::complex-rational-real 448 | ;; :complex-rational-imag ::complex-rational-imag 449 | ;; :complex-rational ::complex-rational 450 | )) 451 | 452 | (s/def ::poly 453 | (s/with-gen #(instance? Poly %) 454 | (fn [] (gen/fmap #(->Poly 'x (list 455 | (list 5 (nth % 0)) 456 | (list 4 (nth % 1)) 457 | (list 3 (nth % 2)) 458 | (list 0 (nth % 3)))) 459 | (gen/tuple 460 | (s/gen ::mono) 461 | (s/gen ::mono) 462 | (s/gen ::mono) 463 | (s/gen ::mono)))))) 464 | 465 | (s/def ::all (s/or :mono ::mono 466 | ;; :poly ::poly 467 | )) 468 | 469 | (s/fdef add 470 | :args (s/cat :a ::all :b ::all) 471 | :ret any?) 472 | (s/fdef sub 473 | :args (s/cat :a ::all :b ::all) 474 | :ret any?) 475 | (s/fdef mul 476 | :args (s/cat :a ::all :b ::all) 477 | :ret any?) 478 | (s/fdef div 479 | :args (s/cat :a ::all :b ::all) 480 | :ret any?) 481 | (s/fdef equal? 482 | :args (s/cat :a ::all :b ::all) 483 | :ret boolean?) 484 | 485 | ;; (stest/summarize-results (stest/check `add)) 486 | ;; (s/exercise-fn `add) 487 | 488 | ;; (stest/summarize-results (stest/check `sub)) 489 | ;; (s/exercise-fn `sub) 490 | 491 | ;; (stest/summarize-results (stest/check `mul)) 492 | ;; (s/exercise-fn `mul) 493 | 494 | ;; (stest/summarize-results (stest/check `div)) 495 | ;; (s/exercise-fn `div) 496 | 497 | ;; (stest/summarize-results (stest/check `equal?)) 498 | ;; (s/exercise-fn `equal?) 499 | --------------------------------------------------------------------------------