dependent types (and other ideas for guaranteeing correctness with types)

Post on 20-Feb-2017

233 Views

Category:

Software

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Dependent Types and other ideas for guaranteeing correctness with types

Radek Pietruszewski @radexp • radex.io

@radexp • radex.io

Static typing is nice

@radexp • radex.io

Expressing guarantees

@radexp • radex.io

Partial functions

@radexp • radex.io

let xs = [1, 2, 3]

xs[0] // => 1 xs[4] // => crash xs[-1] // => crash

@radexp • radex.io

subscript (index: Int) -> Element

-a lot, ..., -1, 0, 1, 2, 3, 4, a lot

@radexp • radex.io

subscript (index: Int) -> Element

-a lot, ..., -1, 0, 1, 2, 3, 4, a lot

@radexp • radex.io

No compile time check

😕

@radexp • radex.io

Prefer total functions to partial functions

@radexp • radex.io

Optionals

@radexp • radex.io

Foo* vs Foo vs Foo?

@radexp • radex.io

Enums

@radexp • radex.io

func move(direction: String)

move("up") move("down") move("wat") // undefined

@radexp • radex.io

enum Direction { case Up, Down, Left, Right }

func move(direction: Direction)

@radexp • radex.io

enum SuggestionViewModel { case Header(String) case Suggestion(Suggestion) }

@radexp • radex.io

Dependent Types

@radexp • radex.io

struct User { var loggedIn: Bool ... }

/// `user` must be logged in! func doSomethingImportant(user: User)

@radexp • radex.io

/// `user` must be logged in! func doSomethingImportant(user: User)

😕User(loggedIn: false)

@radexp • radex.io

User<loggedIn=true>

@radexp • radex.io

Validated

github.com/Ben-G/Validated

@radexp • radex.io

struct LoggedInValidator: Validator { static func validate(value: User) -> Bool { return value.loggedIn } }

@radexp • radex.io

struct LoggedInValidator: Validator { static func validate(value: User) -> Bool { return value.loggedIn } }

@radexp • radex.io

Validated<User, LoggedInValidator>

User<loggedIn=true>

@radexp • radex.io

typealias LoggedInUser = Validated<User, LoggedInValidator>

@radexp • radex.io

let rawUser = User(loggedIn: false)

let loggedInUser = LoggedInUser(rawUser)

@radexp • radex.io

func doSomethingImportant(user: LoggedInUser)

🙂

@radexp • radex.io

Keep your functions total

@radexp • radex.io

github.com/Ben-G/Validated

bit.do/partial-functions

top related