Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming...

79
Types And Categories Anat Gilboa (@anat_gilboa) 1

Transcript of Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming...

Page 1: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Types And Categories

Anat Gilboa (@anat_gilboa)

1

Page 2: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Background

2

Page 3: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

The Plan

3

Page 4: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

The Plan

https://github.com/hmemcpy/milewski-ctfp-pdf 4

Page 5: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

The Plan

5

Page 6: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

https://chrisdone.com/posts/monads-are-burritos 6

Page 7: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

What to expect

• "Functional Swift"

• Closures

• Types & Categories

7

Page 8: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

8

Page 9: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Swift

Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design

patterns.

— Swift.org

9

Page 10: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Features

• Closures unified with function pointers

• Tuples and multiple return values

• Generics

• Fast and concise iteration over a range or collection

• Structs that support methods, extensions, and protocols

• Functional programming patterns, e.g., map and filter

• Powerful error handling built-in

• Advanced control flow with do, guard, defer, and repeat keywords

10

Page 11: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Features

• Functional programming patterns, e.g., map and filter

• Closures unified with function pointers

11

Page 12: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Functional programming is a programming paradigm

that treats computation as the evaluation of mathematical

functions and avoids changing state and mutable data.

https://en.wikipedia.org/wiki/Functional_programming 12

Page 13: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Functional Programming

Functional programming is a programming paradigmthat treats computation as the evaluation of mathematical

functions and avoids changing state and mutable data.

paradigm. (n) A worldview underlying the theories and methodology of a particular scientific subject

13

Page 14: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Some Paradigms

Procedural (imperative) programming- decomposing problems into a sequence of actions

Object-oriented programming- decomposing problems into self-contained properties and methods to manipulate them

Functional programming- decomposing problems into functions that accept and return immutable values

Generic programming- general purpose algorithms that can be applied to arbitrary types

http://robnapier.net/swift-is-not-functional 14

Page 15: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Higher-order

A higher-order function is a function that does at least one of the following:- takes one or more functions as arguments- returns a function as its result

Examples:- map, flatMap- filter- reduce

15

Page 16: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

map

let values: [Int] = [1, 2, 3, 4]let squaredValues = values.map { $0 * $0 }print(squaredValues) // [1, 4, 9, 16]

16

Page 17: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

http://goshdarnclosuresyntax.com/ 17

Page 18: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Closures

• a self-contained block of functionality that can be passed around and used in code.

• can capture and store references to any constants and variables from the context in which they are defined.

18

Page 19: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

extension UIView {

open class func animate(withDuration duration: TimeInterval, animations: @escaping () -> Swift.Void, completion: ((Bool) -> Swift.Void)? = nil) // delay = 0.0, options = 0

}

19

Page 20: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

class MyView: UIView { let label = UILabel() //... func update(title: NSAttributedString, color: UIColor, animated: Bool) { UIView.transition(with: self, duration: animated ? 0.5 : 0, options: .transitionCrossDissolve, animations: { self.label.attributedText = title self.backgroundColor = color }, completion: { completed in if completed == true { print("we finished the animation!") } }) }}

20

Page 21: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Promise

• A Promise is a way to represent a value that will exist (or will fail with an error) at some point in the future.

• Similar to how an Optional represents a value that may or may not exist.

let usersPromise = fetchUsers() // Promise<[User]>usersPromise.then({ users in self.users = users})

https://github.com/khanlou/Promise 21

Page 22: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Promise

struct User { let age: Int let givenName: String}

func fetchUsers() -> Promise<[User]> { // get a list of users return Promise(value: users)}

fetchUsers() .then { users -> [User] in return users.filter { $0.givenName == "Lucy" } } .catch { error in displayError(error) }

https://github.com/khanlou/Promise 22

Page 23: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Promise

fetchUsers() .then { users -> [User] in return users.filter { $0.givenName == "Lucy" } } .then { lucys -> Promise<[User]> in guard let firstLucy = lucys.first else { return Promise(error: LucyError()) } return fetchFollowers(for: firstLucy) }.then { [weak self] followers in guard followers.count > 0 else { return } self?.doSomething(with: followers) } .catch { error in displayError(error) }

23

Page 24: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

.then { users -> ??? in //???}.then { lucys -> ??? in //???}

24

Page 25: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Type ✔ "

25

Page 26: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Type Systems

Comprised of a collection of rules that assign a property (type) to various constructs in a computer program, such as variables, expressions, functions or modules

26

Page 27: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

So What?

27

Page 28: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

28

Page 29: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

A monad is just a monoid in the category of endofunctors, what's

the problem?— James Iry, Brief, Incomplete and Mostly Wrong History of

Programming Languages

29

Page 30: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

"All told, a monad in X is just a monoid in the category of endofunctors of X, with product × [operation] replaced by composition of endofunctors and unit set by the identity endofunctor."— Saunders MacLane, Categories for the Working Mathematician

http://www-news.uchicago.edu/releases/05/050421.maclane.jpg 30

Page 31: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Category

A category consists of:- a collection of objects- a collection of morphisms - every morphism has a source and object

31

Page 32: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Composition 101

func incr(_ x: Int) -> Int { return x + 1}

func square(_ x: Int) -> Int { return x * x}

square(incr(2)) // 9

32

Page 33: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Composition 101

f(x) = x2

g(x) = x + 1

(f ⚬ g)(x) = f(g(x)) = (x + 1)2

(f ⚬ g)(2) = f(g(2)) = (2 + 1)2 = 9

33

Page 34: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Category Laws

34

Page 35: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Recap

• ✅ category:

• objects and arrows

• associativity:

• f : a → b, g : b → c and h : c → d, h ∘ (g ∘ f) = (h ∘ g) ∘ f

• identity:

• 1x : x → x

35

Page 36: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Category example: Set

• big

• small

36

Page 37: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

A monad is a monoid is the category of endofunctors

✅ category⬜ monoid

37

Page 38: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Monoid

A set M equipped with a binary operation μ: M×M→Mand a special element 1 ∈ Msuch that 1 and x⋅y=μ(x,y) satisfy the usual axioms of associativity:* (x⋅y)⋅z=x⋅(y⋅z)and the left and right unit laws:* 1⋅x = x = x⋅1

38

Page 39: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Recap

• ✅ category

• ✅ monoid:

• a set

• associativity:

• f : a → b, g : b → c and h : c → d, h ∘ (g ∘ f) = (h ∘ g) ∘ f

• identity:

• 1x : x → x

39

Page 40: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

A monad is a monoid is the category of endofunctors

✅ category✅ monoid⬜ monoidal category

40

Page 41: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Monoidal Category

A monoidal category is a category equipped with some notion of ‘tensor product’ (bifunctor): ⊗

41

Page 42: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Product

Set of pairs (Cartesian product)

typealias A = String

typealias B = Int

struct Product<A,B> {

let a: A

let b: B

}

let projectionA: (Product<A,B>) -> A = { $0.a }

let projectionB: (Product<A,B>) -> B = { $0.b }

let prod = Product(a: "Hello", b: 3)

projectionA(prod) // "Hello"

projectionB(prod) // 3

42

Page 43: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Product

43

Page 44: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Coproduct

typealias A = Stringtypealias B = Int

enum Coproduct<A,B> { case a(A) case b(B)}

let injectA: (A) -> Coproduct<A,B> = { .a($0) }let injectB: (B) -> Coproduct<A,B> = { .b($0) }

let left = "left"let right = 3injectA(left) // a("left")injectB(right) // b(3)

44

Page 45: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Coproduct

45

Page 46: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Either

enum Either<String, Int> {

case Left(String)

case Right(Int)

}

let possibleInjectionA: Either<String,Int> = .Left("Hello")

let possibleInjectionB: Either<String,Int> = .Right(3)

46

Page 47: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Optional

enum Optional<T> {

case None

case Some(T)

}

47

Page 48: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Result

enum Result<T> { case Value(value: T) case Error(error: Error)}

48

Page 49: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Bifunctor

⊗ : C × C → C

49

Page 50: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Monoidal Category

• ✅ category

• ✅ monoid

• ✅ monoidal category:

• Objects and arrows

• Product

• associativity

• identity

• Coproduct

• associativity

• identity

50

Page 51: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

A monad is a monoid is the category of endofunctors

✅ category✅ monoid✅ monoidal category⬜ functor

51

Page 52: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Functor

• Structure-preserving mapping between categories

• Objects to objects

• Arrows to arrows

52

Page 53: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Functor

A simple intuition is that a Functor represents a “container” of some sort, along with the ability to apply a function uniformly to

every element in the container.

For example, a list is a container of elements, and we can apply a function to every element of a list, using map.

https://wiki.haskell.org/Typeclassopedia 53

Page 54: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Functor

enum Result<T> { case Value(value: T) case Error(error: Error)}

extension Result { func map<U>(f: (T) -> U) -> Result<U> { switch self { case let .Value(value): return Result<U>.Value(value: f(value)) case let .Error(error): return Result<U>.Error(error: error) } }}

54

Page 55: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

http://adit.io/posts/2013-04-17-functors,applicatives,andmonadsin_pictures.html 55

Page 56: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

http://adit.io/posts/2013-04-17-functors,applicatives,andmonadsin_pictures.html 56

Page 57: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

A monad is just a monoid in the category of endofunctors

✅ category✅ monoid✅ monoidal category✅ functor

57

Page 58: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Endofunctors

An endofunctor is a functor from one category back to the same category

58

Page 59: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

59

Page 60: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

60

Page 61: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Example

func map<U>(f: (T) -> U) -> Result<U>

61

Page 62: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Example

func map(f: (Data) -> Result<String>) -> Result<Result<String>>

62

Page 63: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Example

func map(f: (Data) -> Result<String>) -> Result<Result<String>>

extension Result { static func flatten<T>(result: Result<Result<T>>) -> Result<T> { switch result { case let .Value(innerResult): return innerResult case let .Error(error): return Result<T>.Error(error: error) } }}

http://www.javiersoto.me/post/106875422394 63

Page 64: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

A monad is just a monoid in the category of endofunctors

64

Page 65: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

If you can define flatMap for a type, the type is often called a monad.

— Chris Eidhof

http://chris.eidhof.nl/post/monads-in-swift/ 65

Page 66: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Result

extension Result { func flatMap<U>(f: T -> Result<U>) -> Result<U> { return Result.flatten(map(f)) }}

66

Page 67: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

A monad is just a monoid in the category of endofunctors

✅ category✅ monoid✅ monoidal category✅ functor✅ endofunctor

67

Page 68: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

HOW ! THIS ! ALL ! CONNECTS !

68

Page 69: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

69

Page 70: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Programming Languages, Dr. Westley Weimer 70

Page 71: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Types

71

Page 72: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Types

• A set of values

• A set of valid operations on those values

72

Page 73: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Type Checking

• Statically

• Dynamically

• Untyped

73

Page 74: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Hole-driven (or compiler-driven) development with types

seeing the compiler not as an enemy you have to fight, but as a tool that guides you almost magically to a solution for your problem, one step at a

time, using types.

— Ole Begemann

.then { users -> ??? in //???}.then { lucys -> ??? in //???}

https://oleb.net/blog/2015/07/swift-type-system/ 74

Page 75: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Embracing the Type System

Hole-driven development is a fantastic technique for modeling data structures and data transformations

https://oleb.net/blog/2015/07/swift-type-system/ 75

Page 76: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Take aways

• No need to fear the definition of a "monad"

• We use monads all the time

• Swift has monads built in, but extending your type to be a monad is simple

• There's lots more category theory out there

• Closures and maps allow us to embrace our type system

76

Page 77: Types And Categories - Teki Con · 2018-04-30 · Swift Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.

Thanks!

77