├── .gitignore ├── LICENSE ├── README.md ├── doc └── intro.md ├── project.clj ├── src └── hindley_milner │ ├── eval.clj │ ├── syntax.clj │ └── types.clj └── test └── hindley_milner ├── eval_test.clj ├── syntax_test.clj └── types_test.clj /.gitignore: -------------------------------------------------------------------------------- 1 | pom.xml 2 | *jar 3 | /lib/ 4 | /classes/ 5 | /targets/ 6 | .lein-deps-sum 7 | /.lein-env 8 | /.lein-failures 9 | /.nrepl-port 10 | /target/ 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 Washington 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 | # hindley-milner 2 | 3 | An implementation of Algorithm W (and an interpreter) for a simple 4 | lambda-calculus. 5 | 6 | ## Assumptions 7 | 8 | You have installed [Leiningen](http://leiningen.org/#install) and [Git](http://git-scm.com/book/en/Getting-Started-Installing-Git) 9 | 10 | ## Getting Set Up 11 | Clone the repository: 12 | 13 | git clone https://github.com/ericnormand/hindley-milner 14 | 15 | cd hindley-milner 16 | 17 | lein repl 18 | user> 19 | 20 | user> (ns user 21 | (:refer-clojure :exclude [eval]) 22 | (:require [hindley-milner.syntax :refer :all] 23 | [hindley-milner.eval :refer :all] 24 | [hindley-milner.types :refer :all])) 25 | 26 | 27 | ## Usage - Syntax 28 | 29 | user> '(fn [a] x) 30 | 31 | (fn [a] x) 32 | 33 | user> (lambda? '(fn [a] x)) 34 | 35 | true 36 | 37 | user> (free-vars '(let [a x 38 | b y] 39 | (((z a) b) c))) 40 | 41 | #{'x 'y 'z 'c} 42 | 43 | ## Usage - Evaluation 44 | 45 | user> (interpret env 1) 46 | 47 | 1 48 | 49 | user> (interpret env 50 | '(let [c (dec b) 51 | id (fn a a) 52 | b 2] 53 | (id c))) 54 | 55 | 1 56 | 57 | ## Usage - Type Inference 58 | 59 | user> (infer tenv 1) 60 | 61 | :Integer 62 | 63 | user> (infer* tenv '(if true 1 2)) 64 | 65 | [:Lambda :Integer] 66 | 67 | 68 | user> (let [[_ [_] [_ [_ _ x] y]] 69 | (infer* tenv '(fn [a] 70 | (let [x (fn [b] 71 | (let [y (fn [c] 72 | (a 1))] 73 | (y 2)))] 74 | (x 3))))] 75 | (= x y)) 76 | 77 | true 78 | 79 | 80 | ## Usage - Running Tests 81 | 82 | To run the tests: 83 | 84 | lein test 85 | 86 | 87 | ## Goals 88 | 89 | Pull requests welcome! 90 | 91 | * Implement Hindley-Milner in Clojure (DONE!) 92 | * Learn and teach about type systems 93 | * Discover similarities between Lisp's meta-circular `eval` 94 | and syntax-directed HM. 95 | 96 | ### Non-goals 97 | 98 | * To type check Clojure. 99 | 100 | ## TODO 101 | 102 | * Add support for inferencing multiple bindings in a `let`. 103 | * Add negative tests 104 | * Docstrings 105 | 106 | ## License 107 | 108 | Copyright © 2014 Eric Normand 109 | 110 | Please see http://lispcast.com/Hindley-Milner-in-Clojure for rationale. 111 | 112 | Distributed under the Eclipse Public License either version 1.0 or (at 113 | your option) any later version. 114 | -------------------------------------------------------------------------------- /doc/intro.md: -------------------------------------------------------------------------------- 1 | # Introduction to hindley-milner 2 | 3 | TODO: write [great documentation](http://jacobian.org/writing/great-documentation/what-to-write/) 4 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject hindley-milner "0.1.0-SNAPSHOT" 2 | :description "FIXME: write description" 3 | :url "http://example.com/FIXME" 4 | :license {:name "Eclipse Public License" 5 | :url "http://www.eclipse.org/legal/epl-v10.html"} 6 | :dependencies [[org.clojure/clojure "1.5.1"]]) 7 | -------------------------------------------------------------------------------- /src/hindley_milner/eval.clj: -------------------------------------------------------------------------------- 1 | (ns hindley-milner.eval 2 | (:refer-clojure :exclude [eval]) 3 | (:require [hindley-milner.syntax :refer :all])) 4 | 5 | (defn tramp 6 | "deref recursively." 7 | [x] 8 | (if (instance? clojure.lang.IDeref x) 9 | (recur (deref x)) 10 | x)) 11 | 12 | (defn eval [env exp] 13 | (cond 14 | (atom? exp) 15 | exp 16 | 17 | (variable? exp) 18 | (if (contains? env exp) 19 | (get env exp) 20 | (throw (ex-info (str exp " is not defined.") {}))) 21 | 22 | (application? exp) 23 | (let [[f arg] exp 24 | f* (eval env f) 25 | arg* (eval env arg)] 26 | (delay ((tramp f*) arg*))) 27 | 28 | (lambda? exp) 29 | (let [[_ arg body] exp 30 | fv (free-vars body) 31 | env* (select-keys env fv)] 32 | (fn [x] 33 | (eval (assoc env* arg x) body))) 34 | 35 | (let? exp) 36 | (let [[_ bindings body] exp 37 | binding-pairs (partition 2 bindings) 38 | promises (for [pair binding-pairs] 39 | [pair (promise)]) 40 | env* (reduce (fn [e [[var _] p]] 41 | (assoc e var p)) 42 | env 43 | promises)] 44 | (doseq [[[_ val] p] promises] 45 | (deliver p (eval env* val))) 46 | (eval env* body)) 47 | 48 | :else 49 | (throw (ex-info (str "Not evalable: " exp "::" (type exp)) {:exp exp})))) 50 | 51 | (defn interpret [env exp] 52 | (tramp (eval env exp))) 53 | 54 | (defn interpret* [env exp] 55 | (->> exp 56 | transform-applications 57 | transform-lambdas 58 | (interpret env))) 59 | 60 | (def env {'zero? (fn [x] 61 | (zero? (tramp x))) 62 | 'if (fn [test] 63 | (fn [then] 64 | (fn [else] 65 | (if (tramp test) then else)))) 66 | '* (fn [a] 67 | (fn [b] 68 | (* (tramp a) (tramp b)))) 69 | 'dec (fn [x] 70 | (dec (tramp x))) 71 | 'inc (fn [x] 72 | (inc (tramp x))) 73 | 'pair (fn [a] 74 | (fn [b] 75 | [(tramp a) (tramp b)]))}) 76 | -------------------------------------------------------------------------------- /src/hindley_milner/syntax.clj: -------------------------------------------------------------------------------- 1 | (ns hindley-milner.syntax 2 | (:require [clojure.string :as string] 3 | [clojure.set :as set] 4 | [clojure.walk :as walk])) 5 | 6 | ;; util 7 | (defn vmap [f mp] 8 | (into {} (for [[k v] mp] [k (f v)]))) 9 | 10 | ;; value code 11 | 12 | (defn application? 13 | "Is this form a function application? 14 | Function applications are seqs whose first elements are not 15 | reserved for special forms." 16 | [x] 17 | (and (seq? x) 18 | (not (contains? #{'fn 'let} (first x))))) 19 | 20 | (defn variable? 21 | "Is this form a variable?" 22 | [x] 23 | (symbol? x)) 24 | 25 | (defn lambda? 26 | "Is this form a lambda abstraction? 27 | Lambda abstractions are seqs with 'fn as the first element." 28 | [x] 29 | (and (seq? x) 30 | (= 'fn (first x)))) 31 | 32 | (defn let? 33 | "Is this form a let abstraction? 34 | Let abstractions are seqs with 'let as the first element." 35 | [x] 36 | (and (seq? x) 37 | (= 'let (first x)))) 38 | 39 | (defn atom? 40 | "Atoms are atomic values. Numbers, Booleans, Thunks, and Functions." 41 | [x] 42 | (or 43 | (number? x) 44 | (instance? java.lang.Boolean x) 45 | (instance? clojure.lang.IDeref x) 46 | (fn? x))) 47 | 48 | (defn free-vars 49 | "Calculate the free variables of an expression." 50 | [exp] 51 | (cond 52 | (atom? exp) 53 | #{} 54 | 55 | (variable? exp) 56 | #{exp} 57 | 58 | (application? exp) 59 | (let [[fun arg] exp] 60 | (set/union (free-vars fun) (free-vars arg))) 61 | 62 | (lambda? exp) 63 | (let [[_ arg body] exp] 64 | (disj (free-vars body) arg)) 65 | 66 | (let? exp) 67 | (let [[_ bindings body] exp 68 | bindings* (partition 2 bindings) 69 | vars (map first bindings*) 70 | vals (map second bindings*)] 71 | (set/difference 72 | (reduce set/union 73 | (free-vars body) 74 | (map free-vars vals)) 75 | (set vars))))) 76 | 77 | ;; type code 78 | 79 | (defn type-constant? [x] 80 | (keyword? x)) 81 | 82 | (defn type-variable? [x] 83 | (symbol? x)) 84 | 85 | (defn type-variable 86 | ([] (gensym)) 87 | ([x] 88 | (let [[n] (string/split (name x) #"__")] 89 | (gensym (str n "__"))))) 90 | 91 | (defn type-application? [x] 92 | (vector? x)) 93 | 94 | (defn type-application [n ts] 95 | (vec (cons n ts))) 96 | 97 | (defn type-env? [x] 98 | (map? x)) 99 | 100 | (defn type-env [] 101 | {}) 102 | 103 | (defn type-scheme? [x] 104 | (and 105 | (seq? x) 106 | (= 'forall (first x)))) 107 | 108 | (defn free-types [x] 109 | (cond 110 | (type-constant? x) 111 | #{} 112 | (type-variable? x) 113 | #{x} 114 | (type-application? x) 115 | (let [[n & types] x] 116 | (reduce set/union #{} (map free-types types))) 117 | (type-scheme? x) 118 | (let [[_ vars t] x] 119 | (set/difference (free-types t) (set vars))) 120 | (type-env? x) 121 | (reduce set/union #{} (map free-types (vals x))))) 122 | 123 | (defmacro forall [vars type] 124 | (if (seq vars) 125 | (let [fvs (free-types type) 126 | rplc (set/intersection (set fvs) (set vars)) 127 | bindings (into {} (for [v rplc] 128 | [v (type-variable v)]))] 129 | `(list ~''forall '~(vec (vals bindings)) 130 | '~(walk/postwalk-replace bindings type))) 131 | type)) 132 | 133 | (defn compose-substitution [a b] 134 | (merge (vmap (partial walk/postwalk-replace a) b) 135 | a)) 136 | 137 | (defn transform-applications [exp] 138 | (walk/postwalk 139 | (fn [form] 140 | (if (application? form) 141 | (let [[f & args] form] 142 | (loop [largs args 143 | r f] 144 | (if (seq largs) 145 | (recur (rest largs) (list r (first largs))) 146 | r))) 147 | form)) 148 | exp)) 149 | 150 | (defn transform-lambdas [exp] 151 | (walk/postwalk 152 | (fn [form] 153 | (if (lambda? form) 154 | (let [[_ args body] form] 155 | (loop [rargs (reverse args) 156 | f body] 157 | (if (seq rargs) 158 | (recur (rest rargs) 159 | (list 'fn (first rargs) f)) 160 | f))) 161 | form)) 162 | exp)) 163 | -------------------------------------------------------------------------------- /src/hindley_milner/types.clj: -------------------------------------------------------------------------------- 1 | (ns hindley-milner.types 2 | (:require 3 | [clojure.set :as set] 4 | [clojure.walk :as walk] 5 | [hindley-milner.syntax :refer :all])) 6 | 7 | (defn generalize 8 | "Convert a type into a type scheme by converting free type variables 9 | into existential variables. Has no effect if there are no free 10 | variables." 11 | [env t] 12 | (let [vars (vec (set/difference (free-types t) (free-types env)))] 13 | (if (seq vars) 14 | (list 'forall vars t) 15 | t))) 16 | 17 | (defn instantiate 18 | "Convert a type scheme into a type by replacing existential 19 | variables with unique, concrete type variables. Has no effect on 20 | other types." 21 | [t] 22 | (if (type-scheme? t) 23 | (let [[_ vars t*] t 24 | subst (zipmap vars (map type-variable vars))] 25 | (walk/postwalk-replace subst t*)) 26 | t)) 27 | 28 | (defn vbind [v t] 29 | (if (contains? (free-types t) v) 30 | (throw (ex-info (str "Recursive unification.") {})) 31 | {v t})) 32 | 33 | (defn unify [t1 t2] 34 | (cond 35 | (= t1 t2) 36 | {} 37 | 38 | (and (type-application? t1) 39 | (type-application? t2)) 40 | (let [[n1 & ts1] t1 41 | [n2 & ts2] t2] 42 | (cond 43 | (not= n1 n2) 44 | (throw (ex-info (str "Cannot unify two different type applications: " n1 " and " n2) {})) 45 | 46 | (not= (count ts1) (count ts2)) 47 | (throw (ex-info (str "Cannot unify two type applications with different numbers of types: " t1 " & " t2) {})) 48 | 49 | :else 50 | (reduce (fn [subst [t1 t2]] 51 | (let [subst2 (unify (walk/postwalk-replace subst t1) 52 | (walk/postwalk-replace subst t2))] 53 | (compose-substitution subst2 subst))) 54 | {} 55 | (map vector ts1 ts2)))) 56 | 57 | (type-variable? t1) 58 | (vbind t1 t2) 59 | 60 | (type-variable? t2) 61 | (vbind t2 t1) 62 | 63 | :else 64 | (throw (ex-info (str "Types do not unify: " t1 t2) {})))) 65 | 66 | (defn infer-atom [exp] 67 | (cond 68 | (integer? exp) 69 | :Integer 70 | (instance? Boolean exp) 71 | :Boolean)) 72 | 73 | (defn infer-type [env exp] 74 | (cond 75 | (variable? exp) 76 | (if-let [t (get env exp)] 77 | [{} (instantiate t)] 78 | (throw (ex-info (str "Unbound variable: " exp) {}))) 79 | 80 | (atom? exp) 81 | [{} (infer-atom exp)] 82 | 83 | (lambda? exp) 84 | (let [[_ arg body] exp 85 | arg-t (type-variable arg) 86 | env* (assoc env arg arg-t) 87 | [subst body-t] (infer-type env* body)] 88 | [subst 89 | (walk/postwalk-replace subst [:Lambda arg-t body-t])]) 90 | 91 | (application? exp) 92 | (let [[fun arg] exp 93 | res-t (if (variable? fun) 94 | (type-variable (str (name fun) "-result")) 95 | (type-variable)) 96 | [s1 fun-t] (infer-type env fun) 97 | [s2 arg-t] (infer-type (walk/postwalk-replace s1 env) arg) 98 | s3 (unify (walk/postwalk-replace s2 fun-t) 99 | [:Lambda arg-t res-t])] 100 | [(reduce compose-substitution s3 [s2 s1]) 101 | (walk/postwalk-replace s3 res-t)]) 102 | 103 | ;; I still need to make it work with multiple bindings 104 | (let? exp) 105 | (let [[_ [var val] body] exp] 106 | (if (contains? (free-vars val) var) 107 | (let [tv (type-variable var) 108 | env* (assoc env var tv) 109 | [s1 t1] (infer-type env* val) 110 | s1* (unify tv t1) 111 | [s2 t2] (infer-type (walk/postwalk-replace 112 | (compose-substitution s1 s1*) env*) body)] 113 | [(compose-substitution s2 s1) t2]) 114 | (let [[s1 t1] (infer-type env val) 115 | t* (generalize (walk/postwalk-replace s1 env) t1) 116 | env* (assoc env var t*) 117 | [s2 t2] (infer-type (walk/postwalk-replace s1 env*) body)] 118 | [(compose-substitution s2 s1) t2]))))) 119 | 120 | (def tenv {'zero? [:Lambda :Integer :Boolean] 121 | 'if (forall [a] 122 | [:Lambda :Boolean 123 | [:Lambda a 124 | [:Lambda a a]]]) 125 | '+ [:Lambda :Integer 126 | [:Lambda :Integer :Integer]] 127 | '* [:Lambda :Integer 128 | [:Lambda :Integer :Integer]] 129 | 'dec [:Lambda :Integer :Integer] 130 | 'inc [:Lambda :Integer :Integer] 131 | 'pair (forall [a b] 132 | [:Lambda a 133 | [:Lambda b [:Tuple a b]]]) 134 | 'empty? (forall [a] 135 | [:Lambda [:List a] :Boolean]) 136 | 'rest (forall [a] 137 | [:Lambda [:List a] [:List a]])}) 138 | 139 | (defn infer [env exp] 140 | (let [[subst t] (infer-type env exp)] 141 | (generalize env (walk/postwalk-replace subst t)))) 142 | 143 | (defn infer* [env exp] 144 | (->> exp 145 | transform-applications 146 | transform-lambdas 147 | (infer env))) 148 | -------------------------------------------------------------------------------- /test/hindley_milner/eval_test.clj: -------------------------------------------------------------------------------- 1 | (ns hindley-milner.eval-test 2 | (:refer-clojure :exclude [eval]) 3 | (:require [clojure.test :refer :all] 4 | [hindley-milner.eval :refer :all])) 5 | 6 | (deftest tramp-test 7 | (is (= 1 (tramp (delay (delay (delay (future 1)))))))) 8 | 9 | (deftest interpret-test 10 | (is (= 1 (interpret env 1))) 11 | (is (= 1 (interpret (assoc env 'v 1) 'v))) 12 | (is (= 1 (interpret env '(inc 0)))) 13 | (is (fn? (interpret env '(fn a a)))) 14 | (is (= 1 (interpret env '((fn a a) 1)))) 15 | (is (= 1 (interpret env '((((fn a (fn b (fn c c))) 3) 2) 1)))) 16 | (is (= 1 (interpret env '(let [id (fn a a)] 17 | (id 1))))) 18 | (is (= 1 (interpret env '(let [id (fn a a) 19 | b 1] 20 | (id b))))) 21 | (is (= 1 (interpret env '(let [c (dec b) 22 | id (fn a a) 23 | b 2] 24 | (id c)))))) 25 | (deftest interpret*-test 26 | (is (= 1 (interpret* env 1))) 27 | (is (= 1 (interpret* (assoc env 'v 1) 'v))) 28 | (is (= 1 (interpret* env '(inc 0)))) 29 | (is (fn? (interpret* env '(fn [a] a)))) 30 | (is (= 1 (interpret* env '((fn [a] a) 1)))) 31 | (is (fn? (interpret* env '((fn [a b c] c) 3 2)))) 32 | (is (= 1 (interpret* env '((fn [a b c] c) 3 2 1)))) 33 | (is (= 1 (interpret* env '(let [f (fn [a b c] c)] 34 | (f 3 2 1))))) 35 | (is (= 1 (interpret* env '(let [id (fn [a] a)] 36 | (id 1))))) 37 | (is (= 1 (interpret* env '(let [id (fn [a] a) 38 | b 1] 39 | (id b))))) 40 | (is (= 1 (interpret* env '(let [c (dec b) 41 | id (fn [a] a) 42 | b 2] 43 | (id c))))) ) 44 | -------------------------------------------------------------------------------- /test/hindley_milner/syntax_test.clj: -------------------------------------------------------------------------------- 1 | (ns hindley-milner.syntax-test 2 | (:require [clojure.test :refer :all] 3 | [hindley-milner.syntax :refer :all])) 4 | 5 | (deftest lambda-test 6 | (is (lambda? '(fn [a] x)))) 7 | 8 | (deftest forall-test 9 | (is (= :Integer (forall [] :Integer))) 10 | (let [[forall [var] [l x y]] (forall [a] [:Lambda a a])] 11 | (is (= l :Lambda)) 12 | (is (= x y)) 13 | (is (= x var))) 14 | (let [[forall [a b] [l x y]] (forall [a b] [:Lambda a b])] 15 | (is (= l :Lambda)) 16 | (is (= a x)) 17 | (is (= b y)))) 18 | 19 | (deftest free-vars-test 20 | (is (= #{} (free-vars 1))) 21 | (is (= #{'a} (free-vars 'a))) 22 | (is (= #{'a 'b 'c} (free-vars '((a b) c)))) 23 | (is (= #{'x} (free-vars '(fn a x)))) 24 | (is (= #{'x 'y 'z 'c} (free-vars '(let [a x 25 | b y] 26 | (((z a) b) c)))))) 27 | 28 | (deftest free-types-test 29 | (is (= #{} (free-types :Int))) 30 | (is (= #{'x} (free-types 'x))) 31 | (is (= #{'a 'b} (free-types [:Xyz 'a 'b :Int]))) 32 | (is (= #{} (free-types (forall [a b] 33 | [:Lambda a b])))) 34 | (is (= #{'b} (free-types (forall [a] 35 | [:Lambda a b])))) 36 | (is (= #{} (free-types (forall [a] 37 | :Int))))) 38 | 39 | (deftest apply-substitution-test 40 | ) 41 | -------------------------------------------------------------------------------- /test/hindley_milner/types_test.clj: -------------------------------------------------------------------------------- 1 | (ns hindley-milner.types-test 2 | (:require [clojure.test :refer :all] 3 | [hindley-milner.syntax :refer :all] 4 | [hindley-milner.types :refer :all])) 5 | 6 | (deftest infer-type-test 7 | 8 | (is (= :Integer (infer tenv 1))) 9 | (is (= :Boolean (infer tenv true))) 10 | (is (= :Boolean (infer tenv false))) 11 | (is (= :Integer (infer (assoc tenv 'v (forall [] :Integer)) 12 | 'v))) 13 | (is (= :Integer (infer (assoc tenv 'v :Integer) 14 | 'v))) 15 | 16 | (let [[forall [var] [l x y]] (infer tenv '(fn x x))] 17 | (is (= l :Lambda)) 18 | (is (= x y)) 19 | (is (= x var))) 20 | 21 | (is (= :Boolean (infer tenv '(zero? 1)))) 22 | (is (= [:Lambda :Integer :Integer] (infer tenv '(* 1)))) 23 | (is (= :Integer (infer tenv '((* 1) 2)))) 24 | 25 | (is (= :Integer (infer tenv '(let [a 1] a)))) 26 | (is (= :Boolean (infer tenv '(let [a 10] (zero? a))))) 27 | 28 | (is (= :Integer (infer tenv '(let [id (fn x x)] (id 1))))) 29 | 30 | (is (= :Integer (infer tenv '(let [a 7] 31 | (let [b (fn x ((+ a) x))] 32 | (b 90)))))) 33 | 34 | (is (= [:Tuple :Integer :Boolean] 35 | (infer tenv '((pair 1) false))))) 36 | 37 | (deftest infer-type*-test 38 | (is (= [:Tuple :Integer :Boolean] 39 | (infer* tenv '(pair 1 false)))) 40 | (let [[_ [_] [_ [_ _ x] y]] 41 | (infer* tenv '(fn [a] 42 | (let [x (fn [b] 43 | (let [y (fn [c] 44 | (a 1))] 45 | (y 2)))] 46 | (x 3))))] 47 | (is (not (nil? x))) 48 | (is (= x y))) 49 | ) 50 | --------------------------------------------------------------------------------