<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Joakim Ahnfelt-Rønne on Medium]]></title>
        <description><![CDATA[Stories by Joakim Ahnfelt-Rønne on Medium]]></description>
        <link>https://medium.com/@ahnfelt?source=rss-3be9e7bc720f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*6n_Zyhq8nRJJ57rxfJRMFA.jpeg</url>
            <title>Stories by Joakim Ahnfelt-Rønne on Medium</title>
            <link>https://medium.com/@ahnfelt?source=rss-3be9e7bc720f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:11:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahnfelt/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Async/await inference in Firefly]]></title>
            <link>https://ahnfelt.medium.com/async-await-inference-in-firefly-c736c5c216b0?source=rss-3be9e7bc720f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c736c5c216b0</guid>
            <category><![CDATA[type-inference]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Joakim Ahnfelt-Rønne]]></dc:creator>
            <pubDate>Wed, 16 Feb 2022 19:08:31 GMT</pubDate>
            <atom:updated>2022-02-16T19:08:31.161Z</atom:updated>
            <content:encoded><![CDATA[<p>Firefly is a new general purpose programming language that tries to achieve convenience and safety at the same time, by using pervasive dependency injection. There is no global access to the file system, the network, other processes or devices. Instead, you access these through a system object that is passed to the main function, which in turn can pass this object to other methods. The idea is to give the programmer fine grained control over which parts of the code can access what (Log4Shell anybody?), without introducing monads or other explicit effect tracking.</p><p>As it turns out, this mechanism enables colorless async/await.</p><p>Because all I/O is accessed via dependency injection, a top level function call can only be asynchronous if it’s called with an asynchronous argument. This leads to the first rule of inferring async/await in Firefly:</p><p><strong>Rule 1:</strong> Top level function calls can only be asynchronous if they’re called with asynchronous arguments. Every top level function gets a sync version and an async version. If one of the arguments is async, the async version is called; otherwise the sync version is called.</p><p>Inner functions may also <em>capture</em> async objects and call them. However, that can only come, directly or indirectly, from the arguments of the top level function. This leads to the second rule.</p><p><strong>Rule 2:</strong> Inner functions are async if they call an async function. Such functions always come, directly or indirectly, from the arguments of the top level method.</p><p>When you call a function with multiple arguments, the function may update one argument with the the capabilities of the other though mutation. This also applies to the return value, which may be e.g. a lambda functions that updates one of the captured arguments when it’s later called, possibly based on the concrete arguments given when calling the lambda function.</p><p><strong>Rule 3:</strong> All arguments and the return values are potentially async if any of the arguments are async. The return value may later cause the arguments to become async.</p><p>Using an effect type inference based on these rules, Firefly automatically infers which calls are definitely synchronous, and which calls are possibly asynchronous. It’s colorless: Programmers never have to annotate functions as async, and never have to manually await. In fact, Firefly has <em>no syntax</em> for specifying such things.</p><p>Let’s take a final look at the output of the static analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fXB0bJ3fnQg8-ZdN.png" /></figure><p>The calls that may be async are automatically identified. This means you can write straightforward code that looks like it’s blocking, and still get all the benefits of asynchronous I/O.</p><p>In part 2, we infer async/await on a concrete code example and see how it works under the hood:</p><p><strong>Read part 2:</strong> <a href="https://www.ahnfelt.net/async-await-inference-in-firefly-part-2/">https://www.ahnfelt.net/async-await-inference-in-firefly-part-2/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c736c5c216b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Row polymorphism crash course]]></title>
            <link>https://ahnfelt.medium.com/row-polymorphism-crash-course-587f1e7b7c47?source=rss-3be9e7bc720f------2</link>
            <guid isPermaLink="false">https://medium.com/p/587f1e7b7c47</guid>
            <dc:creator><![CDATA[Joakim Ahnfelt-Rønne]]></dc:creator>
            <pubDate>Fri, 09 Jul 2021 18:00:56 GMT</pubDate>
            <atom:updated>2021-07-09T21:10:33.683Z</atom:updated>
            <content:encoded><![CDATA[<p>With type inference, structural records types can make a statically typed language feel almost like a scripting language, without giving up type safety:</p><pre>// Works for any record with the fields width, height : Float<br>area2d v = v.width * v.height</pre><p>Row polymorphism can be used to implement this, and can also be used for polymorphic variants, effect systems and stack types in concatenative languages. This post gives a few quick examples of how it works.</p><p>Suppose we have two functions that work on row polymorphic records:</p><pre>f : forall row1. {a: Int, …row1} -&gt; Int<br>g : forall row2. {b: String, …row2} -&gt; Int</pre><p>And we want to figure out the type of the following function:</p><pre>h x = f x + g x</pre><p>As usual, we <em>instantiate</em> the <strong>forall</strong>-bound variables — in this case <em>row variables</em> by replacing them with fresh row variables.<br>The instantiated types for the occurrences of <strong>f</strong> and <strong>g</strong> here are thus:</p><pre>f : {a: Int, …row3} -&gt; Int<br>g : {b: String, …row4} -&gt; Int</pre><p>Since <strong>x</strong> occurs as the argument of both <strong>f</strong> and <strong>g</strong>, we know two things about it:</p><pre>x : {a: Int, …row3}<br>x : {b: String, …row4}</pre><p>Thus we must perform unification on those two types:</p><pre>{a: Int, …row3} = {b: String, …row4}</pre><p>To solve this, we create a substitution where each of the row variables contain the opposite records fields, as well as a fresh row variable <strong>row5</strong>:</p><pre>row3 = {b: String, …row5}<br>row4 = {a: Int, …row5}</pre><p>Applying this substitution to the equation above gives us:</p><pre>{a: Int, b: String, …row5} = {b: String, a: Int, …row5}</pre><p>Sorting the fields lexicographically by field name gives us syntactically equality:</p><pre>{a: Int, b: String, …row5} = {a: Int, b: String, …row5}</pre><p>The final type for <strong>h</strong> is thus (after generalization):</p><pre>h : forall row5. {a: Int, b: String, …row5} -&gt; Int</pre><p>And thus we have inferred a row polymorphic record type by hand.</p><p><em>One thing I like about using row polymorphism for inferring structural types is that it only involves equalities — no inequalities as you get with subtyping, which are much harder to solve for.</em></p><p>Now, what if <strong>f</strong> and <strong>g </strong>instead had the same field name, but with different types?</p><pre>f : {a: Int, …row3} -&gt; Int<br>g : {a: String, …row4} -&gt; Int</pre><p>Then we’d need to unify these:</p><pre>{a: Int, …row3} = {a: String, …row4}</pre><p>When unifying two records, the types of the common fields are unified, and <em>not included</em> in the substitution of <strong>row3</strong> and <strong>row4</strong>.</p><p>In this case, there is exactly one common field <strong>a</strong>, with a different type on each side. That leads to a unification failure, and thus a type error:</p><pre>Int = String</pre><p>We’ve discovered an error in our program! The field <strong>a </strong>can’t be both an Int and a String.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=587f1e7b7c47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type Inference by Example, Part 7]]></title>
            <link>https://ahnfelt.medium.com/type-inference-by-example-part-7-31e1d1d05f56?source=rss-3be9e7bc720f------2</link>
            <guid isPermaLink="false">https://medium.com/p/31e1d1d05f56</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[type-inference]]></category>
            <dc:creator><![CDATA[Joakim Ahnfelt-Rønne]]></dc:creator>
            <pubDate>Sat, 18 Apr 2020 08:18:59 GMT</pubDate>
            <atom:updated>2020-04-18T20:40:37.766Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*t400kmJalw-EQkCA5TdSeQ.png" /><figcaption>At the end of this article, we can infer generic types like these.</figcaption></figure><p>Continuing where we left off in <a href="https://medium.com/swlh/type-inference-by-example-part-6-52c58bd29f1d">part 6</a>, let’s add in mutually recursive functions with generics.</p><p>Consider the following example:</p><pre>function even(x) { return x == 0 || odd(x - 1); }<br>function odd(x) { return x != 0 &amp;&amp; even(x - 1); }</pre><p>We say that these functions are <em>mutually recursive:</em> even calls odd and odd calls even. Because of that, we can’t infer the types of each function in isolation — we must consider both at the same time. Let’s add support for such mutually recursive functions to our syntax tree:</p><pre><strong>case class </strong>EFunctions(<br>  functions : List[GenericFunction],<br>  body : Expression<br>) <strong>extends </strong>Expression</pre><p>The functions is a list of functions that may call each other, and they are in scope in body.</p><p>The next thing is that these functions may be <em>generic</em> — that is, they may have a type parameter list &lt;…&gt;, as in the classic map function:</p><pre>function map&lt;A, B&gt;(array : Array&lt;A&gt;, f : A =&gt; B) : Array&lt;B&gt;</pre><p>A generic function has a name and optionally a generic type. For the parameters and body, we’ll use the lambda function defined earlier in the series:</p><pre><strong>case class </strong>GenericFunction(<br>    name : String,<br>    typeAnnotation : Option[GenericType],<br>    lambda : Expression<br>)</pre><p>The GenericType is just a list of type parameters and an ordinary type:</p><pre><strong>case class </strong>GenericType(<br>    generics : List[String],<br>    uninstantiatedType : Type<br>)</pre><p>It’s called uninstantiatedType because it may mention some of the type parameters from generics, and we’ll have to remember to <em>instantiate</em> that type, replacing the type parameters with fresh type variables on use.</p><p>Finally, when we use a variable, for example map, we need the ability to specify the type arguments, as in map&lt;Int, String&gt;(...), so we add generics to our variables:</p><pre><strong>case class </strong>EVariable(<br>    name : String,<br>    generics : List[Type] = <em>List</em>()<br>) <strong>extends </strong>Expression</pre><h3>Inferring the generic types</h3><p>Earlier in the series, our environment looked like this: Map[String, Type]. We’re going to change Type to GenericType, so that variables can be generic in our environment. Now our infer function looks like this:</p><pre><strong>def </strong>infer(<br>    environment : Map[String, GenericType],<br>    expectedType : Type,<br>    expression : Expression<br>) : Expression = expression <strong>match </strong>{</pre><p>Whenever we encounter a variable, we’ll look up the variable in the environment and get its generic type back. We then replace each type parameter by a fresh type variable to get an ordinary type. If the user has specified the type arguments explicitly, we constrain each of these fresh type variables to be equal to the corresponding user supplied type.</p><pre><strong>case </strong>EVariable(name, generics) =&gt;<br>  <strong>val </strong>genericType = environment(name)<br>  <strong>val </strong>newGenerics = genericType.generics.map(_ =&gt; <br>    freshTypeVariable()<br>  )<br>  <strong>val </strong>instantiation = genericType.generics.zip(newGenerics).toMap<br>  <strong>val </strong>variableType = instantiate(<br>    instantiation, <br>    genericType.uninstantiatedType<br>  )<br>  <strong>if</strong>(generics.nonEmpty) {<br>    assert(generics.size == genericType.generics.size)<br>    <strong>for</strong>((t, v) &lt;- generics.zip(newGenerics)) {<em><br>      typeConstraints </em>+= CEquality(t, v)<br>    }<br>  }<br>  <em>typeConstraints </em>+= CEquality(expectedType, variableType)<br>  EVariable(name, newGenerics)</pre><p>Now we get to the mutually recursive, possibly generic functions. This is where we find out which type parameters our functions should have.</p><p>The first thing we need to do is to create an environment recursiveEnvironment that’s only for checking the mutually recursive functions. In this environment, the functions without a user supplied type annotation will get a fresh type variable instead. Then we use this environment to infer the type of each of the functions.</p><p>Now the functions — at least those without user supplied type annotations — have an ordinary type with type variables in them. We want to find out which of these type variables we can convert into type parameters to make the function generic. Before we do that, we solve all the outstanding type constraints to update our substitution, so we call solveConstraints().</p><p>After that, we call generalize on each of the functions that don’t have a user supplied type annotation. This finds out which type variables are safe to turn into type parameters. Now we have our GenericTypes for the functions.</p><p>The only thing that’s missing is to put these into an environment for inferring the body, where these functions are in scope.</p><pre><strong>case </strong>EFunctions(functions, body) =&gt;</pre><pre>  <strong>val </strong>recursiveEnvironment = <br>    environment ++ functions.map { function =&gt;<br>      function.name -&gt; function.typeAnnotation.getOrElse(<br>        GenericType(<em>List</em>(), freshTypeVariable())<br>      )<br>    }.toMap</pre><pre>  <strong>val </strong>ungeneralizedFunctions = functions.map { function =&gt;<br>    <strong>val </strong>uninstantiatedType =<br>      recursiveEnvironment(function.name).uninstantiatedType<br>    function.copy(lambda = infer(<br>      recursiveEnvironment, <br>      uninstantiatedType, <br>      function.lambda<br>    ))<br>  }</pre><pre>  solveConstraints()</pre><pre>  <strong>val </strong>newFunctions = ungeneralizedFunctions.map { function =&gt;<br>    <strong>if</strong>(function.typeAnnotation.nonEmpty) function <strong>else </strong>{<br>      <strong>val </strong>functionType = <br>        recursiveEnvironment(function.name).uninstantiatedType<br>      <strong>val </strong>(newTypeAnnotation, newLambda) = generalize(<br>        environment, <br>        functionType, <br>        function.lambda<br>      )<br>      function.copy(<br>        typeAnnotation = Some(newTypeAnnotation), <br>        lambda = newLambda<br>      )<br>    }<br>  }</pre><pre>  <strong>val </strong>newEnvironment = <br>    environment ++ newFunctions.map { function =&gt;<br>      function.name -&gt; function.typeAnnotation.get<br>    }.toMap</pre><pre>  <strong>val </strong>newBody = infer(newEnvironment, expectedType, body)</pre><pre>  EFunctions(newFunctions, newBody)</pre><p>That’s it for the changes to the infer function.</p><pre>} // the rest of this function remains the same</pre><h3>Instantiation and generalization</h3><p>We’ve done some of the work to instantiate a GenericType to a Type already, so all we need to do in the instantiate function is to replace all the occurrences of the type parameter with the corresponding type:</p><pre><strong>def </strong>instantiate(<br>  instantiation : Map[String, Type], <br>  t : Type<br>) : Type = t <strong>match </strong>{<br>  <strong>case </strong>_ <strong>if </strong>instantiation.isEmpty =&gt; t<br>  <strong>case </strong>TVariable(i) <strong>if </strong><em>substitution</em>(i) != TVariable(i) =&gt; <br>    instantiate(instantiation, <em>substitution</em>(i))<br>  <strong>case </strong>TConstructor(name, generics) =&gt;<br>    instantiation.get(name).map { instantiationType =&gt;<br>      <strong>assert</strong>(generics.isEmpty)<br>      instantiationType<br>    }.getOrElse {<br>      TConstructor(name, generics.map(t =&gt;<br>        instantiate(instantiation, t)<br>      ))<br>    }<br>  <strong>case </strong>_ =&gt; t<br>}</pre><p>The generalize function has the task of finding out which type variables in a type are safe to turn into type parameters.</p><p>So which ones are safe? Well, those type variables that won’t be constrained later in the code. The only way for the later code to get one of the type variables in the type to further constrain is if it occurs in the environment. That means we simply need exclude the type variables that occur in the environment.</p><p>In order to give these type parameters reasonable names, we consume from an iterator that produces names like A, B, C, etc.</p><p>We then replace those type variables with type parameters wherever they occur in the type and the expression. Along with that, we return a GenericType with the type parameters.</p><pre><strong>def </strong>generalize(<br>  environment : Map[String, GenericType],<br>  t : Type,<br>  expression : Expression<br>) : (GenericType, Expression) = {<br>  <strong>val </strong>genericTypeVariables = <br>    freeInType(t) -- freeInEnvironment(environment)<br>  <strong>val </strong>genericNames = genericTypeVariables.map(i =&gt; <br>    i -&gt; <em>genericParameterNames</em>.next()<br>  ).toList<br>  <strong>val </strong>localSubstitution = <em>substitution</em>.clone()<br>  <strong>for</strong>((i, name) &lt;- genericNames) {<br>    localSubstitution(i) = TConstructor(name)<br>  }<br>  <strong>val </strong>newExpression = <br>    substituteExpression(localSubstitution, expression)<br>  <strong>val </strong>newType = substitute(localSubstitution, t)<br>  GenericType(<br>    genericNames.map { <strong>case </strong>(_, name) =&gt; name }, <br>    newType<br>  ) -&gt; newExpression<br>}</pre><p>The freeInType function finds all the type variables that occur in a type. The freeInGenericType and freeInEnvironment does the same for generic types and the environment:</p><pre><strong>def </strong>freeInType(t : Type) : SortedSet[Int] = t <strong>match </strong>{<br>  <strong>case </strong>TVariable(i) <strong>if </strong><em>substitution</em>(i) != TVariable(i) =&gt; <br>    freeInType(<em>substitution</em>(i))<br>  <strong>case </strong>TVariable(i) =&gt; SortedSet(i)<br>  <strong>case </strong>TConstructor(_, generics) =&gt; <br>    generics.map(freeInType).fold(SortedSet()) { _ ++ _ }<br>}<br><br><strong>def </strong>freeInGenericType(t : GenericType) : SortedSet[Int] = {<br>  freeInType(t.uninstantiatedType)<br>}<br><br><strong>def </strong>freeInEnvironment(<br>  environment : Map[String, GenericType]<br>) : SortedSet[Int] = {<br>  environment.values.map(freeInGenericType).<br>    fold(SortedSet[Int]()) { _ ++ _ }<br>}</pre><p>And we’re done.</p><h3>Demo</h3><p>Now that we have the a version of our type inference that can infer generic types, it’s time to see it in action. View and run the code so far <a href="https://scastie.scala-lang.org/Ahnfelt/6suj8tM3S8aCofyzJVObsA/6">here</a>.</p><p>Stay tuned for part 8, where we’ll take a look at overloading via type classes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31e1d1d05f56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type Inference by Example, Part 6]]></title>
            <link>https://medium.com/swlh/type-inference-by-example-part-6-52c58bd29f1d?source=rss-3be9e7bc720f------2</link>
            <guid isPermaLink="false">https://medium.com/p/52c58bd29f1d</guid>
            <category><![CDATA[type-inference]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[Joakim Ahnfelt-Rønne]]></dc:creator>
            <pubDate>Wed, 15 Apr 2020 06:17:01 GMT</pubDate>
            <atom:updated>2020-04-18T08:29:38.125Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*qlnLuapvTZsDn1J0DFZlUQ.png" /><figcaption>Wow, I’m glad we didn’t have to type all that!</figcaption></figure><p>Continuing where we left off in <a href="https://medium.com/@joakim.ahnfelt/type-inference-by-example-part-5-25d7a7c66ca6">part 5</a>, let’s extend the language and reconstruct the missing type annotations in the syntax tree.</p><p>First, we’ll extend the lambda function syntax and application so that it supports multiple arguments.</p><pre><strong>case class </strong>ELambda(<br>  parameters : List[Parameter],<br>  returnType : Option[Type],<br>  body : Expression<br>) <strong>extends </strong>Expression<br><br><strong>case class </strong>EApply(<br>  function : Expression,<br>  arguments : List[Expression]<br>) <strong>extends </strong>Expression</pre><p>Apart from multiple arguments, we’ve also added optional type annotations. The Parameter contains a name and an optional type.</p><pre><strong>case class </strong>Parameter(<br>  name : String,<br>  typeAnnotation : Option[Type]<br>)</pre><p>We’ll introduce let for local variables:</p><pre><strong>case class </strong>ELet(<br>  name : String,<br>  typeAnnotation : Option[Type],<br>  value : Expression,<br>  body : Expression<br>) <strong>extends </strong>Expression<br><br><strong>case class </strong>EVariable(<br>  name : String<br>) <strong>extends </strong>Expression</pre><p>And literals for Ints, Strings and Arrays:</p><pre><strong>case class </strong>EInt(<br>  value : Int<br>) <strong>extends </strong>Expression<br><br><strong>case class </strong>EString(<br>  value : String<br>) <strong>extends </strong>Expression<br><br><strong>case class </strong>EArray(<br>  itemType : Option[Type],<br>  items : List[Expression],<br>) <strong>extends </strong>Expression</pre><h3>Adding in the missing types</h3><p>Now that we have type annotations in the syntax tree, we need the inference to be able to return a new syntax tree with all the type annotations filled in.</p><pre><strong>def </strong>infer(<br>  environment : Map[String, Type],<br>  expectedType : Type,<br>  expression : Expression<br>) : Expression = expression <strong>match </strong>{</pre><p>Another change is that instead of returning the inferred type of the expression, we’ll take in the expected type instead. Note that we can still infer the type of the whole expression by using a fresh type variable as the expected type.</p><p>Let’s start with the lambda function. First, we’ll use fresh type variables in place of any missing type annotations. Then, we’ll infer the types in the lambda body expression in an environment containing the lambda parameters. Finally, we’ll constrain the expected type to be a function type of the appropriate arguments and return type. Finally, we return a lambda functions where all the missing type annotations have been filled in.</p><pre><strong>case </strong><em>ELambda</em>(parameters, returnType, body) =&gt;<br>  <strong>val </strong>newReturnType = returnType.getOrElse(freshTypeVariable())<br>  <strong>val </strong>newParameterTypes = <br>    parameters.map(_.typeAnnotation.getOrElse(freshTypeVariable()))<br>  <strong>val </strong>newParameters = parameters.zip(newParameterTypes).map { <br>    <strong>case </strong>(p, t) =&gt; p.copy(typeAnnotation = Some(t))<br>  }<br>  <strong>val </strong>newEnvironment = environment ++ newParameters.map { p =&gt;<br>    p.name -&gt; p.typeAnnotation.get<br>  }<br>  <strong>val </strong>newBody = infer(newEnvironment, newReturnType, body)<br>  <em>typeConstraints </em>+= <em>CEquality</em>(expectedType,<br>    <em>TConstructor</em>(<strong>s&quot;Function$</strong>{parameters.size}<strong>&quot;</strong>, <br>        newParameterTypes ++ <em>List</em>(newReturnType)<br>    )<br>  )<br>  <em>ELambda</em>(newParameters, Some(newReturnType), newBody)</pre><p>For function application, we’ll generate fresh type variables for the arguments, and use these to construct a function type with those argument types and the expected type as the return type. We then infer the missing types in the function expression, expecting this function type. Finally, we infer the missing types of each argument, and return the new application where the missing type annotations have been filled in.</p><pre><strong>case </strong><em>EApply</em>(function, arguments) =&gt;<br>  <strong>val </strong>argumentTypes = arguments.map(_ =&gt; freshTypeVariable())<br>  <strong>val </strong>functionType = <em>TConstructor</em>(<strong>s&quot;Function$</strong>{arguments.size}<strong>&quot;</strong>, <br>    argumentTypes ++ <em>List</em>(expectedType)<br>  )<br>  <strong>val </strong>newFunction = infer(environment, functionType, function)<br>  <strong>val </strong>newArguments = arguments.zip(argumentTypes).map { <br>    <strong>case </strong>(argument, t) =&gt; infer(environment, t, argument)<br>  }<br>  <em>EApply</em>(newFunction, newArguments)</pre><p>For variables, all we have to do is look up the type in the environment and constrain the expected type to be equal to that type.</p><pre><strong>case </strong><em>EVariable</em>(name) =&gt;<br>  <strong>val </strong>variableType = environment(name)<br>  <em>typeConstraints </em>+= <em>CEquality</em>(expectedType, variableType)<br>  expression</pre><p>For let bindings, we generate a fresh type variable if the type annotation is missing, and then infer the value expecting this type. We then check the body of the let in an environment extended with the let bound variable. Finally, we return a let binding where all the missing type annotations have been filled in.</p><pre><strong>case </strong><em>ELet</em>(name, typeAnnotation, value, body) =&gt;<br>  <strong>val </strong>newTypeAnnotation = <br>    typeAnnotation.getOrElse(freshTypeVariable())<br>  <strong>val </strong>newValue = infer(environment, newTypeAnnotation, value)<br>  <strong>val </strong>newEnvironment = environment.updated(name, newTypeAnnotation)<br>  <strong>val </strong>newBody = infer(newEnvironment, expectedType, body)<br>  <em>ELet</em>(name, Some(newTypeAnnotation), newValue, newBody)</pre><p>For Int and String literals, we just constrain the expected type.</p><pre><strong>case </strong><em>EInt</em>(_) =&gt;<br>  <em>typeConstraints </em>+= <em>CEquality</em>(expectedType, <em>TConstructor</em>(<strong>&quot;Int&quot;</strong>))<br>  expression<br><br><strong>case </strong><em>EString</em>(_) =&gt;<br>  <em>typeConstraints </em>+= <em>CEquality</em>(expectedType, <em>TConstructor</em>(<strong>&quot;String&quot;</strong>))<br>  expression</pre><p>For Array literals, we generate a fresh type variable if the type annotation is missing, and then infer each array item expecting this type. We then constrain the expected type to be an array of that item type. Finally, we return an array literal where all the missing type annotations have been filled in.</p><pre><strong>case </strong><em>EArray</em>(itemType, items) =&gt;<br>  <strong>val </strong>newItemType = itemType.getOrElse(freshTypeVariable())<br>  <strong>val </strong>newItems = items.map(item =&gt; <br>    infer(environment, newItemType, item)<br>  )<br>  <em>typeConstraints </em>+= <em>CEquality</em>(expectedType, <br>    <em>TConstructor</em>(<strong>&quot;Array&quot;</strong>, <em>List</em>(newItemType))<br>  )<br>  <em>EArray</em>(Some(newItemType), newItems)</pre><p>That’s it for the infer function:</p><pre>}</pre><h3>Substitution in expressions</h3><p>After running the infer function, we have an expression with all the types filled in, but they’re still mostly type variables. We can solve the type constraints as in part 5 to get the right substitution, but we’ll still need a function to traverse the syntax tree and apply the substitution to all the types.</p><pre><strong>def </strong>substituteExpression(<br>  expression : Expression<br>) : Expression = expression <strong>match </strong>{<br><br>  <strong>case </strong><em>ELambda</em>(parameters, returnType, body) =&gt;<br>    <strong>val </strong>newReturnType = returnType.map(substitute)<br>    <strong>val </strong>newParameters = parameters.map(p =&gt; p.copy(<br>      typeAnnotation = p.typeAnnotation.map(substitute))<br>    )<br>    <strong>val </strong>newBody = substituteExpression(body)<br>    <em>ELambda</em>(newParameters, newReturnType, newBody)<br><br>  <strong>case </strong><em>EApply</em>(function, arguments) =&gt;<br>    <strong>val </strong>newFunction = substituteExpression(function)<br>    <strong>val </strong>newArguments = arguments.map(substituteExpression)<br>    <em>EApply</em>(newFunction, newArguments)<br><br>  <strong>case </strong><em>EVariable</em>(_) =&gt;<br>    expression<br><br>  <strong>case </strong><em>ELet</em>(name, typeAnnotation, value, body) =&gt;<br>    <strong>val </strong>newTypeAnnotation = typeAnnotation.map(substitute)<br>    <strong>val </strong>newValue = substituteExpression(value)<br>    <strong>val </strong>newBody = substituteExpression(body)<br>    <em>ELet</em>(name, newTypeAnnotation, newValue, newBody)<br><br>  <strong>case </strong><em>EInt</em>(_) =&gt;<br>    expression<br><br>  <strong>case </strong><em>EString</em>(_) =&gt;<br>    expression<br><br>  <strong>case </strong><em>EArray</em>(itemType, items) =&gt;<br>    <strong>val </strong>newItemType = itemType.map(substitute)<br>    <strong>val </strong>newItems = items.map(substituteExpression)<br>    <em>EArray</em>(newItemType, newItems)<br><br>}</pre><p>And we’re done.</p><h3>Demo</h3><p>Now that we have the a version of our type inference that can add in the missing type annotations, it’s time to see it in action. View and run the code so far <a href="https://scastie.scala-lang.org/Ahnfelt/hnUjXzGaRQ2MdduTo3PkRw/34">here</a>.</p><p>Stay tuned for <a href="https://medium.com/@joakim.ahnfelt/type-inference-by-example-part-7-31e1d1d05f56">part 7</a>, where we’ll add in mutually recursive functions with generics.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52c58bd29f1d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/type-inference-by-example-part-6-52c58bd29f1d">Type Inference by Example, Part 6</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type Inference by Example, Part 5]]></title>
            <link>https://ahnfelt.medium.com/type-inference-by-example-part-5-25d7a7c66ca6?source=rss-3be9e7bc720f------2</link>
            <guid isPermaLink="false">https://medium.com/p/25d7a7c66ca6</guid>
            <category><![CDATA[type-inference]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[Joakim Ahnfelt-Rønne]]></dc:creator>
            <pubDate>Mon, 13 Apr 2020 17:50:09 GMT</pubDate>
            <atom:updated>2020-04-15T06:17:54.889Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*ucOQOzTaFRsx5fdS1ZHXOw.png" /><figcaption>First demo—type inference for lambda calculus.</figcaption></figure><p>Continuing where we left off in <a href="https://medium.com/@joakim.ahnfelt/type-inference-by-example-part-4-3aaca6400c7e">part 4</a>, let’s finish implementing a first version of the type inference — and see a small demo.</p><p>The first thing we’ll need is a language to infer types for. Let’s start with the lambda calculus:</p><pre><strong>sealed abstract class </strong>Expression<br><strong>case class </strong>ELambda(x : String, e : Expression) <strong>extends </strong>Expression<br><strong>case class </strong>EApply(e1 : Expression, e2 : Expression) <strong>extends </strong>Expression<br><strong>case class </strong>EVariable(x : String) <strong>extends </strong>Expression</pre><p>We’ll also need a representation of constraints. For now, we only have equality constraints:</p><pre><strong>sealed abstract class </strong>Constraint<br><strong>case class </strong>CEquality(t1 : Type, t2 : Type) <strong>extends </strong>Constraint</pre><p>As we go though the syntax tree and generate constraints, we’ll need somewhere to store them:</p><pre><strong>val </strong><em>typeConstraints </em>= ArrayBuffer[Constraint]()</pre><p>For generating fresh type variables, recall that we chose a representation where each type variable is initially bound to itself in the substitution:</p><pre><strong>def </strong>freshTypeVariable() : TVariable = {<br>    <strong>val </strong>result = <em>TVariable</em>(<em>substitution</em>.length)<br>    <em>substitution </em>+= result<br>    result<br>}</pre><h3>Inferring types of expressions</h3><p>Now we need to go through the expression and generate the constraints that are to be solved, and find out what the type of the expression is:</p><pre><strong>def </strong>inferType(<br>    expression : Expression,<br>    environment : Map[String, Type]<br>) : Type = expression <strong>match </strong>{</pre><p>This function takes in an expression and an environment and returns a type. The environment is used to keep track of the type of variables during inference.</p><p>For lambda functions, we generate a fresh type variable t1 for the variable and add it to the environment. Then we infer the type t2 of the lambda body in this environment. The final type is the function type t1 =&gt; t2:</p><pre><strong>case </strong><em>ELambda</em>(x, e) =&gt;<br>    <strong>val </strong>t1 = freshTypeVariable()<br>    <strong>val </strong>environment2 = environment.updated(x, t1)<br>    <strong>val </strong>t2 = inferType(e, environment2)<br>    <em>TConstructor</em>(<strong>&quot;Function1&quot;</strong>, <em>List</em>(t1, t2))</pre><p>When we encounter a variable, we look it up in the environment and return that type:</p><pre><strong>case </strong><em>EVariable</em>(x) =&gt;<br>    environment(x)</pre><p>For application (as in, calling a function with an argument) we first infer the type of the function and the argument, and generate a fresh type variable for the return type. Then we constrain the function type to be, well, a function type from the type of the argument to the return type:</p><pre><strong>case </strong><em>EApply</em>(e1, e2) =&gt;<br>    <strong>val </strong>t1 = inferType(e1, environment)<br>    <strong>val </strong>t2 = inferType(e2, environment)<br>    <strong>val </strong>t3 = freshTypeVariable()<br>    <em>typeConstraints </em>+= <br>        <em>CEquality</em>(t1, <em>TConstructor</em>(<strong>&quot;Function1&quot;</strong>, <em>List</em>(t2, t3)))<br>    t3</pre><p>That’s it for the inferType function:</p><pre>}</pre><h3>Finishing up</h3><p>The type we get back from inferType is likely a type variable at this point. In order to find out the concrete type, we’ll need to solve the constraints and then apply the substitution to the type.</p><p>Since we only have equality constraints right now, we can simply use unification we developed in <a href="https://medium.com/@joakim.ahnfelt/type-inference-by-example-part-4-3aaca6400c7e">part 4</a> to solve them:</p><pre><strong>def </strong>solveConstraints() : Unit = {<br>    <strong>for</strong>(<em>CEquality</em>(t1, t2) &lt;- <em>typeConstraints</em>) unify(t1, t2)<br>    <em>typeConstraints</em>.clear()<br>}</pre><p>Applying the substitution is done by following the chain of subsitutions and substituting the generics recursively:</p><pre><strong>def </strong>substitute(t : Type) : Type = t <strong>match </strong>{<br>    <strong>case </strong><em>TVariable</em>(i) <strong>if </strong><em>substitution</em>(i) != <em>TVariable</em>(i) =&gt; <br>        substitute(<em>substitution</em>(i))<br>    <strong>case </strong><em>TConstructor</em>(name, generics) =&gt; <br>        <em>TConstructor</em>(name, generics.map(t =&gt; substitute(t)))<br>    <strong>case </strong>_ =&gt; t<br>}</pre><p>And we’re done.</p><h3>Demo</h3><p>Now that we have the first version of our type inference, it’s time to see it in action. View and run the code so far <a href="https://scastie.scala-lang.org/Ahnfelt/WWuVjbBGRWCQNwPnOU7Q0A">here</a>.</p><p>Stay tuned for <a href="https://medium.com/@joakim.ahnfelt/type-inference-by-example-part-6-52c58bd29f1d">part 6</a>, where we’ll extend the type inference to a bigger language and insert the missing types into the syntax tree.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25d7a7c66ca6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type Inference by Example, Part 4]]></title>
            <link>https://ahnfelt.medium.com/type-inference-by-example-part-4-3aaca6400c7e?source=rss-3be9e7bc720f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3aaca6400c7e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[type-inference]]></category>
            <dc:creator><![CDATA[Joakim Ahnfelt-Rønne]]></dc:creator>
            <pubDate>Sun, 12 Apr 2020 07:01:00 GMT</pubDate>
            <atom:updated>2020-04-14T21:23:56.211Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*kr6HQIyrMOOjYAWK5h_dEg.png" /><figcaption>Using unification to turn each equality constraint into a substitution.</figcaption></figure><p>Continuing where we left off in <a href="https://medium.com/@joakim.ahnfelt/type-inference-by-example-part-3-e9e2c27f1fb2">part 3</a>, let’s take a look at unification.</p><p>The first thing we’ll need is a representation for types. Let’s look at the types we’ve seen so far:</p><ul><li>Int — a plain type</li><li>Array&lt;Int&gt; — a generic type</li><li>(Int, Int) =&gt; Int — a function type</li><li>$1 — a type variable</li></ul><p>The Array thing up there is called a <em>type constructor — not to be confused with constructors in object oriented programming. </em>A type constructor is something that takes type parameters — Array is a type constructor, and when given a type parameter, it becomes a type: Array&lt;Int&gt;.</p><p>The function type =&gt; is <em>also</em> a type constructor. When given its type parameters, it becomes a type: (Int, Int) =&gt; Int. To make this more clear, we’ll name function types FunctionN internally, where N is the number of arguments it takes, e.g. Function2&lt;Int, Int, Int&gt;. The last Int here is the return type of the function.</p><p>And if we squint a bit, we can say that Int is a <em>nullary</em> type constructor. Given no type parameters at all, it becomes a type: Int. Thus we arrive at the following representation:</p><pre><strong>sealed abstract class </strong>Type</pre><pre><strong>case class </strong>TConstructor(<br>  name : String, <br>  generics : List[Type] = <em>List</em>()<br>) <strong>extends </strong>Type</pre><pre><strong>case class </strong>TVariable(<br>  index : Int<br>) <strong>extends </strong>Type</pre><p>This is Scala code. The sealed modifier says that there are no subclasses apart from those listed here. A case class can be used as a dumb carrier for data, where each field is public and immutable by default. Let’s see how our types look in this internal representation:</p><ul><li>Int — TConstructor(&quot;Int&quot;)</li><li>Array&lt;Int&gt; — TConstructor(&quot;Array&quot;, List(TConstructor(&quot;Int&quot;)))</li><li>(Int, Int) =&gt; Int — TConstructor(&quot;Function2&quot;, List(TConstructor(&quot;Int&quot;), TConstructor(&quot;Int&quot;), TConstructor(&quot;Int&quot;)))</li><li>$1 — TVariable(1)</li></ul><h3>Back to unification.</h3><blockquote>What is unification? Unification is an algorithm that takes two types and finds a substitution that makes them equal, if such a substitution exists.</blockquote><p>While inferring types, the substitution will grow as we unify types. Recalling that a substitution maps type variables to types, and type variables are identified by integers, we’ll use an expanding array for this:</p><pre><strong>val </strong>substitution<em> </em>= ArrayBuffer[Type]()</pre><p>We’ll choose a substitution where each type variable is initially substituted with itself, i.e.substitution(x) == TypeVariable(x).</p><p>The unification itself is simple:</p><ol><li>Given two TConstructors, check that their name is equal and that they have the same number of type parameters. Then do a pointwise unification of the type arguments.</li><li>Given a TVariable and another type, check if the type variable has been bound to something else than itself in the substitution. If so, unify whatever it’s bound to with the other type. Otherwise, update the unification by binding the type variable to the other type.</li></ol><p>When binding a type variable, we must perform an <em>occurs check </em>to avoid constructing an infinite type such as $1 := Array&lt;$1&gt;.</p><h3>The unification algorithm in code.</h3><p>The unify function takes in two types and pattern matches on them.</p><pre><strong>def </strong>unify(t1 : Type, t2 : Type) : Unit = (t1, t2) <strong>match </strong>{</pre><p>If we have two TConstructors, we check that their name is equal and that they have the same number of type parameters. Then we do a pointwise unification of the type arguments.</p><pre><strong>case </strong>(<em>TConstructor</em>(name1,generics1),<em>TConstructor</em>(name2,generics2))=&gt;<br>  assert(name1 == name2)<br>  assert(generics1.size == generics2.size)<br>  <strong>for</strong>((t1, t2) &lt;- generics1.zip(generics2)) unify(t1, t2)</pre><p>If both sides are the same type variable, do nothing.</p><pre><strong>case</strong> (<em>TVariable</em>(i), <em>TVariable</em>(j)) <strong>if</strong> i == j =&gt; // do nothing</pre><p>If one of the types is a type variable that’s bound in the substitution, use unify with that type instead.</p><pre><strong>case </strong>(<em>TVariable</em>(i), _) <strong>if </strong><em>substitution</em>(i) != <em>TVariable</em>(i) =&gt;<br>  unify(<em>substitution</em>(i), t2)<br><strong>case </strong>(_, <em>TVariable</em>(i)) <strong>if </strong><em>substitution</em>(i) != <em>TVariable</em>(i) =&gt;<br>  unify(t1, <em>substitution</em>(i))</pre><p>Otherwise, if one of the types is an unbound type variable, bind it to the other type. Remember to do an occurs check to avoid constructing infinite types.</p><pre><strong>case </strong>(<em>TVariable</em>(i), _) =&gt;<br>  assert(!occursIn(i, t2))<br>  <em>substitution</em>(i) = t2<br><strong>case </strong>(_, <em>TVariable</em>(i)) =&gt;<br>  assert(!occursIn(i, t1))<br>  <em>substitution</em>(i) = t1</pre><p>The assertions should be replaced with proper error reporting, but that is a topic for another day.</p><pre>} // That&#39;s it for unification</pre><p>We’ll need the occursIn method as well, which simply recurses into the type and checks if the type variable index in question occurs:</p><pre><strong>def </strong>occursIn(index : Int, t : Type) : Boolean = t <strong>match </strong>{<br>  <strong>case </strong><em>TVariable</em>(i) <strong>if </strong><em>substitution</em>(i) != <em>TVariable</em>(i) =&gt; <br>    occursIn(index, <em>substitution</em>(i))<br>  <strong>case </strong><em>TVariable</em>(i) =&gt; <br>    i == index<br>  <strong>case </strong><em>TConstructor</em>(_, generics) =&gt; <br>    generics.exists(t =&gt; occursIn(index, t))<br>}</pre><p>And we’re done.</p><p>Stay tuned for <a href="https://medium.com/@joakim.ahnfelt/type-inference-by-example-part-5-25d7a7c66ca6">part 5</a>, where we’ll finish up the first version of the type inference.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aaca6400c7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type Inference by Example, Part 3]]></title>
            <link>https://ahnfelt.medium.com/type-inference-by-example-part-3-e9e2c27f1fb2?source=rss-3be9e7bc720f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9e2c27f1fb2</guid>
            <category><![CDATA[type-inference]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Joakim Ahnfelt-Rønne]]></dc:creator>
            <pubDate>Sat, 11 Apr 2020 05:24:32 GMT</pubDate>
            <atom:updated>2020-04-13T09:45:50.296Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*qJCBHAGYhaZVmY-OKLKtsg.png" /><figcaption>Inferring types for generic calls</figcaption></figure><p>Continuing where we left off in <a href="https://medium.com/@joakim.ahnfelt/type-inference-by-example-part-2-46933a75a116">part 2</a>, we’ll now consider calling a generic function:</p><pre>function map&lt;A, B&gt;(array : Array&lt;A&gt;, body : A =&gt; B) : Array&lt;B&gt;</pre><p>So this is the classic map function that applies a lambda function body to each element of the array and returns a new array with the results. Note that map takes two <em>type parameter</em>s, A and B.</p><p>Here’s a function that squares each element of an array:</p><pre>function square(items) {<br>    return map(items, x =&gt; x * x);<br>}</pre><p>Now, to add in the missing type annotations, we first must <em>instantiate</em> the type for map — that is, create a new copy of the function signature where every type<em> parameter</em> is replaced with a fresh type <em>variable</em>:</p><pre>function map&lt;$3, $4&gt;(array : Array&lt;$3&gt;, body : $3 =&gt; $4) : Array&lt;$4&gt;</pre><p>While adding the missing type annotations, we make the generics explicit at the call site of map:</p><pre>function square(items : $1) : $2 {<br>    return map&lt;$3, $4&gt;(items, (x : $5) =&gt; x * x);<br>}</pre><p>The first parameter of our instantiated map has type Array&lt;$3&gt;, so we get the following constraint:</p><pre>$1 == Array&lt;$3&gt;</pre><p>Considering the lambda function, and assuming that * : (Int, Int) =&gt; Int, we get the duplicate constraint:</p><pre>$5 == Int<br>$5 == Int</pre><p>And from the return type of * we know that the return type of the lambda must be Int, such that the full type of the lambda becomes $5 =&gt; Int. It should be the same type as the second parameter to map, so we get the constraint:</p><p>($5 =&gt; Int) == ($3 =&gt; $4)</p><p>From the return statement, we know that the return type of square is the same as the return type of map:</p><p>$2 == Array&lt;$4&gt;</p><p>Now we have all the constraints:</p><pre>$1 == Array&lt;$3&gt;<br>$5 == Int<br>$5 == Int<br>($5 =&gt; Int) == ($3 =&gt; $4)<br>$2 == Array&lt;$4&gt;</pre><p>Since ($5 =&gt; Int) == ($3 =&gt; $4) has the same type constructor =&gt; on both sides, we can replace it by two simpler constraints $5 == $3 and Int == $4:</p><pre>$1 == Array&lt;$3&gt;<br>$5 == Int<br>$5 == Int<br>$5 == $3<br>Int == $4<br>$2 == Array&lt;$4&gt;</pre><p>Unification does this simplification internally — we’ll get to the algorithm in a bit — and yields us the following substitution:</p><pre>$1 := Array&lt;Int&gt;<br>$2 := Array&lt;Int&gt;<br>$3 := Int<br>$4 := Int<br>$5 := Int</pre><p>Applying the substitution to our syntax tree, we get:</p><pre>function square(items : Array&lt;Int&gt;) : Array&lt;Int&gt; {<br>    return map&lt;Int, Int&gt;(items, (x : Int) =&gt; x * x);<br>}</pre><p>And we’re done.</p><p>It’s about time we look at how this is implemented under the hood. Stay tuned for <a href="https://medium.com/@joakim.ahnfelt/type-inference-by-example-part-4-3aaca6400c7e">part 4</a>, where we’ll look at the unification algorithm.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9e2c27f1fb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type Inference by Example, Part 2]]></title>
            <link>https://ahnfelt.medium.com/type-inference-by-example-part-2-46933a75a116?source=rss-3be9e7bc720f------2</link>
            <guid isPermaLink="false">https://medium.com/p/46933a75a116</guid>
            <category><![CDATA[type-inference]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Joakim Ahnfelt-Rønne]]></dc:creator>
            <pubDate>Fri, 10 Apr 2020 19:03:24 GMT</pubDate>
            <atom:updated>2020-04-11T06:00:02.627Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYlI5TuK1ZSAMyeMohrkzQ.png" /><figcaption>Type inference for the empty array.</figcaption></figure><p>Continuing where we left off in <a href="https://medium.com/@joakim.ahnfelt/type-inference-by-example-793d83f98382">part 1</a>, let’s look at a more advanced example that uses local variables and type constructors:</p><pre>function range(from, to) {<br>    let numbers = [];<br>    for(let i = from; i &lt;= to; i++) {<br>        numbers[i - from] = i;<br>    }<br>    return numbers;<br>}</pre><p>As in the previous installment, we add in fresh type variables:</p><pre>function range(from : $1, to : $2) : $3 {<br>    let numbers : $4 = [];<br>    for(let i : $5 = from; i &lt;= to; i++) {<br>        numbers[i - from] = i;<br>    }<br>    return numbers;<br>}</pre><p>Now, on the very first line, we encounter the empty array:</p><pre>let numbers : $4 = [];</pre><p>We know that it should be an Array&lt;… something …&gt;, but what is something? Why, a fresh type variable of course! So for this line, we get the following constraint:</p><pre>$4 == Array&lt;$6&gt;</pre><p>The next line starts the for loop:</p><pre>for(let i : $5 = from; i &lt;= to; i++) {</pre><p>Wow, three statements in one line! Assuming that ++ : Int =&gt; Int, this gives us three constraints:</p><pre>$5 == $1<br>$5 == $2<br>$5 == Int</pre><p>The for loop body assigns a value to an index in numbers:</p><pre>numbers[i - from] = i;</pre><p>This tells us two things: Numbers must be an array, and its element type must be the same as the type of i.</p><pre>$4 == Array&lt;$5&gt;</pre><p>From the same line, assuming — : (Int, Int) =&gt; Int we also constrain the types of i and from to be integers:</p><pre>$5 == Int<br>$1 == Int</pre><p>And finally, from the return statement, we constrain the return type to be the same as the type of number:</p><pre>$3 == $4</pre><p>Now that we have generated all the constraints, let’s consider them all together:</p><pre>$4 == Array&lt;$6&gt;<br>$5 == $1<br>$5 == $2<br>$5 == Int<br>$4 == Array&lt;$5&gt;<br>$5 == Int<br>$1 == Int<br>$3 == $4</pre><p>Again, unification finds a substitution that solve the above system of equations, but let’s first consider the two constraints involving Array. Because $4 is on the other side of both equations, we can simplify that to Array&lt;$6&gt; == Array&lt;$5&gt;. Since both use a type constructor named Array, we check the generic arguments against each other by generating the constraint $6 == $5. And we already have another constraint that $5 == Int. The resulting substitution is thus:</p><pre>$1 := Int<br>$2 := Int<br>$3 := Array&lt;Int&gt;<br>$4 := Array&lt;Int&gt;<br>$5 := Int<br>$6 := Int</pre><p>Applying that to our syntax tree, we get:</p><pre>function range(from : Int, to : Int) : Array&lt;Int&gt; {<br>    let numbers : Array&lt;Int&gt; = [];<br>    for(let i : Int = from; i &lt;= to; i++) {<br>        numbers[i - from] = i;<br>    }<br>    return numbers;<br>}</pre><p>And we’re done.</p><p>Stay tuned for <a href="https://medium.com/@joakim.ahnfelt/type-inference-by-example-part-3-e9e2c27f1fb2">part 3</a>, where we’re going to look generic function calls.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46933a75a116" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type Inference by Example]]></title>
            <link>https://ahnfelt.medium.com/type-inference-by-example-793d83f98382?source=rss-3be9e7bc720f------2</link>
            <guid isPermaLink="false">https://medium.com/p/793d83f98382</guid>
            <category><![CDATA[type-inference]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Joakim Ahnfelt-Rønne]]></dc:creator>
            <pubDate>Fri, 10 Apr 2020 10:59:33 GMT</pubDate>
            <atom:updated>2020-04-11T06:00:50.284Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*dKkr3hNX9j-rKCAvyOvrTA.png" /><figcaption>Type inference, in a nutshell</figcaption></figure><p>If you’re implementing a programming language, you might be pondering how to do type inference. Instead of going through the theory, we’ll go through some examples to build an intuition for how it works, and finally see how to put that into code.</p><p>Consider the following function:</p><pre>function f(x) {<br>    return x * 2;<br>} </pre><p>Since there’s no type annotation for x, and no explicit return type, we&#39;ll have to infer those.</p><p>For this, we can generate two fresh type variables $1 and $2, and add those to our syntax tree:</p><pre>function f(x : $1) : $2 {<br>    return x * 2;<br>} </pre><blockquote>What are type variables? They are integers that act as placeholders for types that we don’t yet know. During type inference, they will be replaced with other types and thus disappear from the syntax tree.</blockquote><p>For the expression x * 2, we know the type of * : (Int, Int) =&gt; Int, so we check x and 2 both with the expected type Int. We know that x : $1 and 2 : Int, so we get the type constraints:</p><pre>$1 == Int<br>Int == Int</pre><blockquote>What are type constraints? They are a way to record things we discover about types and their relations to each other, as we go through the type inference. An equality constraint may literally be represented in code as a pair of types.</blockquote><p>For the statement return x * 2; we know from the type of * that x * 2 returns an Int, and from return that this must be the return type, so we get the constraint:</p><pre>$2 == Int</pre><p>Now that we have a set of constraints, we need to solve them. Perhaps you can solve a system of equality constraints with pen and paper, but the algorithm to do it is called <em>unification</em>. We will cover the implementation of that later, but the output is a substitution — in this case the following:</p><pre>$1 := Int<br>$2 := Int</pre><blockquote>What is a substitution? It’s a map from type variables to types.</blockquote><p>Applying the substitution to our syntax tree — replacing each type variable on the left hand side with the type on the right hand side — we get:</p><pre>function f(x : Int) : Int {<br>    return x * 2;<br>}</pre><p>And we’re done.</p><p>Stay tuned for <a href="https://medium.com/@joakim.ahnfelt/type-inference-by-example-part-2-46933a75a116">part 2</a>, where we’ll go through a more advanced example.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=793d83f98382" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>