A presentation at VanBEAM in March 2016 in Vancouver, BC, Canada by Brooklyn Zelenka
BROOKLYN ZELENKA USE THE @TYPES, LUKE
BROOKLYN ZELENKA SHAMELESS SELF PROMOTION. SHAMELESS. ▸ Organizes C&C, VanFP, VanEE ▸ Last VanEE in person ▸ Co-founder of Robot Overlord Inc, developer at MetaLab ▸ Author of Quark, Algae, and Witchcraft
USE THE @TYPES, LUKE WHAT WE’RE GOING TO COVER ▸ Why types have a bad rep ▸ Elixir’s type system ▸ Typespecs ▸ Dialyxir ▸ Defining our own types ▸ Structs ▸ Parametric polymorphism ▸ Q&A
WHY TYPES HAVE A BAD REP
WHY TYPES HAVE A BAD REP THERE ARE TWO KINDS OF TYPE SYSTEMS. SOME ARE FOR THE COMPILER. OTHERS ARE FOR THE PROGRAMMER. Overheard at LambdaConf 2015
WHY TYPES HAVE A BAD REP TYPES FOR THE COMPILER (EX. C & JAVA) ▸ Boilerplate ▸ Don’t add to the code expressivity ▸ Source of (annoying) warnings
WHY TYPES HAVE A BAD REP TYPES FOR PROGRAMMERS (EX. HASKELL, ELIXIR, SWIFT) ▸ Annotate the meaning of a piece of code ▸ Help to structure your code ▸ Double as documentation ▸ Catch some bugs before you run your code!
ELIXIR’S TYPE SYSTEM
ELIXIR HAS “WEAK” DYNAMIC TYPES. “Weak” doesn’t imply bad
ELIXIR’S TYPE SYSTEM WEAK, DYNAMIC TYPES ▸ Type inference at run time ▸ Static analysis tools do exist (Dialyxr) ▸ Determine code behaviour through parametric polymorphism
ELIXIR’S TYPE SYSTEM BUILT-IN TYPES ▸ There’s quite a few ▸ Some contain others ▸ ex. integer is contained in number
TYPESPECS
TYPESPECS OPTIONAL, GRADUAL TYPING ▸ ex. @spec add(integer, integer) :: integer ▸ Similar syntax to @doc, etc. ▸ Lives outside of the function definition ▸ Has an “@“ before it ▸ Generates documentation
DIALYXIR (DIALYZER)
DIALYXIR (DIALYZER) DIALYZER IS A STATIC ANALYSIS TOOL THAT IDENTIFIES SOFTWARE DISCREPANCIES SUCH AS TYPE ERRORS, UNREACHABLE CODE, UNNECESSARY TESTS, ETC IN SINGLE ERLANG MODULES OR ENTIRE (SETS OF) APPLICATIONS. erlang.org
DIALYXIR (DIALYZER) HOW TO DIALYZE ▸ Add to mix.exs dependencies ▸ mix deps.get ▸ mix deps.compile ▸ mix dialyzer
DIALYXIR (DIALYZER) EXAMPLE OUTPUT
DEFINING OUR OWN TYPES
DEFINING OUR OWN TYPES CUSTOM TYPE EXAMPLE @type number_with_remark :: {number, String.t} @spec add(number, number) :: number_with_remark def add(x, y), do: {x + y, “You need a calculator to do that?”}
STRUCTS
STRUCTS STRUCT TYPES ▸ Multiple named fields ▸ Can get their own type defmodule Algae.Maybe do @type t :: Just.t | Nothing.t defmodule Nothing do @type t :: %Nothing{} defstruct [] end defmodule Just do @type t :: %Just{just: any} defstruct [:just] end end
PARAMETRIC POLYMORPHISM
PARAMETRIC POLYMORPHISM PROTOCOLS ▸ Give a definition of a function name per data type or struct “type” defimpl Witchcraft.Monoid, for: List do def identity(_list), do: [] def append(as, bs), do: as ++ bs end defimpl Witchcraft.Monoid, for: Map do def identity(_map), do: %{} def append(ma, mb), do: Dict.merge(ma, mb) end
Q&A TIME
View Use the @types, Luke on Notist.
Dismiss
A brief introduction to types in the Elixir programming language