Upgrade to Pro — share decks privately, control downloads, hide ads and more …

A Journey to Type-safe Vectors in F#

A Journey to Type-safe Vectors in F#

cannorin

April 17, 2020
Tweet

More Decks by cannorin

Other Decks in Programming

Transcript

  1. $ whoami cannorin Member of F# Software Foundation Member of

    Ionide Maintainer of / Contributing to: - fsprojects/FSharpPlus - ionide/Ionide-vim - ocaml/ocaml-lsp, etc Visit 7colou.red for more details
  2. SPOILER ALERT! • Type-level naturals and booleans • Efficient and

    type-safe vectors (fixed-length array) • Clean and intuitive syntax to use them • As a vanilla F# library (not as a language extension!)
  3. Type-level Naturals, at the very beginning Now we must bring

    it to the type-level, but how to define addition for this?
  4. This allows us to write overloaded functions Overload resolution =

    Matching against types Exploiting overload resolution
  5. We can also implement type-safe index access thanks to type-level

    naturals, but... Vector implementation, the first try
  6. The Cons (definitely not about the list constructor ) •

    Type naturals are tedious to write by hand (1) • Vector creation is not really type-safe (2)
  7. The solution (also definitely not about that thing in Visual

    Studio) ➔ Create type naturals from compile-time constants ➔ Use tuples and count their arity to create vectors
  8. Creating type naturals from compile-time constants Type Providers: • Compile-time

    type generator, basically • Can take constant values (such as JSON schemas) as input and generate types based on them • Fully integrated into the language = Nice IDE support • No deep dive today, would deserves a separate talk
  9. Here TypeNat<_> and Vector.Get<_> are type providers, which takes an

    integer and generates a specialized type to work with the corresponding type-level natural Creating type naturals from compile-time constants
  10. • Count the arity of a given tuple with type

    naturals • Extract elements from the tuple and store them in an array • All done with overload resolution, with no reflection involved Using tuples for vector creation
  11. Finally, we get this... • Clean, intuitive, and type-safe •

    Very small run-time overhead (no reflection/boxing)
  12. Looks awesome? You can use them soon™! Included as part

    of upcoming FSharpPlus[1] v2.0 release with a lot of familiar and useful functions such as: [1]: https://fsprojects.github.io/FSharpPlus/