ADTs - Algebraic Data Types

Marius Jurgelenas

YGLF@Vilnius 2019

Corvid by Wix

 

What is the meaning of life types?

  • Type inference?
  • Static type checking?
  • Autocomplete suggestions?
  • Catching bugs?

Guess the type

Guess the type

Guess the type

Our brain is very good at inferring types

type OS = Linux or Windows or MacOS

type WorkPlace = Computer and Desk and Chair

type Computer = Hardware and OS

type Furniture = Desk or Chair

Composing types

Logic operations

AND

OR

Fruit Salad

type Fruit Salad = Apple AND Banana AND Cherry

How many different fruit salads can we make?

3 × 2 × 2 = 12

Product

Fruit Salad - a Product type

{

    name: 'John',     // string

    age: 42,              // number

    ownsDog: true // boolean

}

 

 

Person - a Product type

type Fruit Snack = Apple OR Banana OR Cherry

Fruit Snack

How many different snacks can we have?

3 + 2 + 2 = 7

Sum

Fruit Snack - a Sum type

Algebraic Data Types

Product types

Sum types

langauge-agnostic

Are Sum types ok?

type snack =              OR                  OR

type strangeThing =  number OR boolean

const name = "Peter"

Guess the type

Uncought TypeError: Cannot read property 'toUpperCase' of undefined

name.toUpperCase()

if (name) {

    return name.toUpperCase()

} else {

    return "No name!"

}

Matching Types

type name = string OR undefined

The building blocks

  • String
  • Number
  • Boolean
  • Undefined/Null

Thinking in types makes the code better*

* - there is no scientific evidence to proove it

Thank you!

Algebraic Data Types

By Marius Jurgelenas

Algebraic Data Types

Slides for yglf@vilnius 2019

  • 622