F# Type Inference 🪄

Magic type inference of ML languages

magic cat — src

How does type inference work in ML languages like standard-ML, OCAML, F#, Elm, Reason and even Haskell? Let’s call it Magic. How does this kind of magic work?

We are going to take a look at the case of F# but once you learn this concept, you will understand how it works in all ML languages and even in Haskell, or potentially others.

I suggest to follow along and try things in your editor, so you just need a simple brew install dotnet on your mac, winget on windows or follow the guide for your OS. Then run on your cli:

dotnet --version

dotnet fsi // launches F# interactive

>let x = 5;; // type any F# followed by `;;` to execute

>#quit;; // exit fsi

To edit files, you can use VsCode+Ionide extension, Rider or VisualStudio. Just name a new file as and you are ready to go, with alt/option + enter you can select and execute portions of code in the REPL.

Or if you feel lazy try it in your browser.

Variable binding 🍭

The simplest case is for binding is 1 value, this is the kind of magic we all know already. The compiler in a similar fashion as what happens in other languages e.g., C# or typescript, will infer our type for us, in this case, int. No big surprises here.

let x = 5 // int

IDEs will show the type either above or next to the binding expression.

A function binding (wow moment starts!) ⭐️

This case is different from any other languages you know of most likely, but you have to think of it as working in a similar fashion as we have seen before, just stretching a bit your imagination.

let addEleven y = //1. int -> int
y + 11

let addString z = //2. string -> string
z + " world"

How does this work? In practice it can get complicated but I will try to make it simpler for me and for you. Let’s analyse these 2 cases:

  1. The result is something that can be summed to an integer type, so + = , the compiler will resolve the type of to be .
  2. The result has to be , with a similar reasoning: + = string, hence must be a .

Think about this for a second. Have you seen this in other languages? Maybe yes, maybe no. Maybe you tried Elm or Reason languages, and that’s exactly how it works there as well.

No Way

My bet is that it might be something completely new to you. Types are inferred in a chain by the compiler using the ML inference algorithm, for which some smart guys like Milner won academic awards such as the Alan Turing award!

No need to write type annotations in signatures or anywhere! awesome! you can still do it if you feel like ofc, just a bit in the opposite way typescript works, below the proof!

Compare with TS

You can use these 2 online compilers to follow along:

typescript without annotations cannot infer types based on the chain of operations

On the other hand, F# seems to be smarter, as it can infer types using the ML inference algorithm!

F# doesn’t need type annotations, in 90% of the cases the compiler has got you covered!

This means that code looks as slim as JavaScript, but it’s statically typed as C# or Java!

The compiler is in charge! 🤖 ⭐️

When changing return values, your code magically “refactors itself” trying to infer the correct types or, eventually, fails the compilation!

let add5 x = // int -> int 
x + 5

let someWrongFunction () = // compilation error!!!
add5 "hello"

let okAdditionFunction () = // OK! unit -> int
add5 100

A Function of functions! 🐇

In this case, with a higher order function (a.k.a. function of functions) the compiler still infers correctly all values, based on which operator you used and applying the types in the function chain along with it. So, starting from left + 3, the return type must be an , everything on the left must also be an !

let someComplexFunction someFunction argument = // ('a -> int) -> 'a -> int 
someFunction(argument) + 3

This means must return an , but can be a generic type , we don't know yet what type it will be, so it’s automatically generalized.

Generic Without T

No more hassle with <T> in our code, the compiler guesses it for us in most cases, and we can type only where we need to do so and it’s not explicit for the compiler.

The first usage of this function in code will nail it 🔨 down its type! for example

let addOne x = x + 1 // int -> int
let z = someComplexFunction addOne 5 // 9: int

Feel free to play around in your favorite editor or online if you are lazy.

Compare and imagine

Compare this to a more complex scenario and imagine (or try it out)

How does refactoring look like in a language with explicit type signatures like C# or Typescript or Java for example, versus an ML language. Let’s see how a simple add function compares to other languages, here is F#:

let addOne a = a + 1 // int -> int
let addOneShorter = (+1) // int -> int

Compare with Java/C#, we still need to specify signatures along the way

public int AddOne(int a) { // we must supply the signature types
return a + 1;
}

How does this code compare to a dynamic language like JavaScript or python? Here, life seems sweet as we don’t have type signatures!

def addOne(a) = ## shorter, but do we get any type check here? 🐛
a + 1

JavaScript and Typescript, here it seems we can do both, but when adding types, we lose the succinct look of the language. See the section above to revisit this specific comparison…

const addOneFirst = a => a + 1; // any -> any

const addOneSecond = (a: int) => a + 1; // int -> int

At a first glance it might look like F# is similar to JavaScript or python, but can you tell the difference❓

let addOne a = a + 1 // int -> int

Refactoring Code ⛑

Think of very long call chains and nested calls, is it easier to refactor in which language and why? In which language does it feel safer?

My take on refactoring is that it’s usually easier to refactor in dynamic languages, but safer to refactor in static languages, with the cons of having to adjust all signatures and type annotations with some assistant tooling (like rider or ReSharper or IDE refactoring assistants).

In F# and ML languages in general it’s both easy and safe to refactor, without the need of external tooling, as the type inference engine will walk through your code while changing it, and constantly give you compiler feedback if anything went wrong along the chain.

Boomer* sheet to compare types

I quickly sketched a table with subjective pros and cons in this language comparison table.

Legend: 🍏good, 🍌meh, 🍊nah.

*LOC refers to only lines of code per type annotations / signatures

Don’t forget to give F# a try if you haven’t yet!

Links on the topic

--

--

jkone27.github.io

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store