Slide 1

Slide 1 text

Container types and how to use them Krzysztof Siejkowski

Slide 2

Slide 2 text

Questions are welcome!

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

Almost 5 years ago…

Slide 7

Slide 7 text

Result Result A E context: possible error instance of type A failure (usually error)

Slide 9

Slide 9 text

No content

Slide 12

Slide 12 text

Either Either A B context: one of two values instance of type A instance of type B

Slide 15

Slide 15 text

No content

Slide 16

Slide 16 text

flatMap A (A) -> Container B A Container + (A) -> Container = Container

Slide 17

Slide 17 text

map A (A) -> B B A B Container + (A) -> B = Container

Slide 18

Slide 18 text

!"

Slide 19

Slide 19 text

Slide 20

Slide 20 text

reduce A A Context related side-effect Container => A or side-effect

Slide 21

Slide 21 text

Slide 22

Slide 22 text

zip C A B A B (A, B) -> C (Container, Container) + (A, B) -> C => Container C

Slide 23

Slide 23 text

unzip C A B A B C -> (A, B) Container + (C) -> (A, B) => (Container, Container) C

Slide 24

Slide 24 text

!"

Slide 25

Slide 25 text

flatMap compactMap A (A) -> Optional B A Container + (A) -> Optional = Container B B

Slide 26

Slide 26 text

Slide 27

Slide 27 text

No content

Slide 29

Slide 29 text

Context describes the constraints of your logic

Slide 30

Slide 30 text

• nil / null • failure / error / exception • lazy evaluation • unknown number of values • asynchronous operation • … many more!

Slide 31

Slide 31 text

No content

Slide 32

Slide 32 text

No content

Slide 33

Slide 33 text

No content

Slide 34

Slide 34 text

let interestingData = networkClient .fetchData() .flatMap { validateStatusCode($0) } .flatMap { deserialize($0) } .map { getSubsetOfData($0) } .reduce { handleSideEffect($0) }

Slide 35

Slide 35 text

No content

Slide 36

Slide 36 text

Scott Wlaschin, “Railway Oriented Programming” https://www.slideshare.net/ScottWlaschin/railway-oriented-programming

Slide 37

Slide 37 text

Scott Wlaschin, “Railway Oriented Programming” https://www.slideshare.net/ScottWlaschin/railway-oriented-programming

Slide 38

Slide 38 text

Many contexts One API

Slide 39

Slide 39 text

optionalValue .map { ... } .flatMap { ... } asynchronousValue .map { ... } .flatMap { ... } multipleValues .map { ... } .flatMap { ... } possibleErrorValue .map { ... } .flatMap { ... }

Slide 40

Slide 40 text

No content

Slide 41

Slide 41 text

No content

Slide 42

Slide 42 text

As a user, I want to see all my Github repos written in Swift language

Slide 43

Slide 43 text

1. Fetch data from Github 2. Deserialize 3. Filter Swift repos

Slide 44

Slide 44 text

githubClient .fetch(.repos, for: user) .map { deserialize($0) } .filter { $0.isSwiftRepo }

Slide 45

Slide 45 text

1. Fetch data from Github extension URLSession { func dataTask( with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void ) -> URLSessionDataTask }

Slide 46

Slide 46 text

1. Fetch data from Github completionHandler => Future (Data?, URLResponse?, Error?) => Result Future>

Slide 47

Slide 47 text

2. Deserialize Response is a JSON object in form of an array of repos: [ { “name”: “repo_name”, ... }, ... deserialize: (Data) throws -> [Data] throws -> [Repo]

Slide 48

Slide 48 text

2. Deserialize deserialize: (Data) throws -> [Data] throws -> [Repo] => (Data) -> Result<[Data], DeserializationError> -> Result<[Result], DeserializationError> Future], DeserializationError >, NetworkError >>

Slide 49

Slide 49 text

3. Filter Swift repos filter: (Repo) -> Bool repos.filter { (repo: Repo) -> Bool in repo.language == "Swift" }

Slide 50

Slide 50 text

3. Filter Swift repos let repos: Future], DeserializationError >, NetworkError >> = githubClient.fetch(.repos, for: user) .map { deserialize($0) } repos.filter { }

Slide 51

Slide 51 text

Future< Result< Result< Array< Result< Repo, DeserializationError > >, DeserializationError >, NetworkError > > ❌

Slide 52

Slide 52 text

No content

Slide 53

Slide 53 text

What’s the difference? Optional A ∅ Either A Void

Slide 54

Slide 54 text

You can write a transform! Optional A ∅ Either A Void Optional A ∅ Either A Void

Slide 55

Slide 55 text

Validated A E E E E E E Result A E

Slide 56

Slide 56 text

extension Result { func asValidated() -> Validated { ... } } Future< Validated< Validated< Array>, DeserializationError >, NetworkError > >

Slide 57

Slide 57 text

sequence A A Container1> => Container2>

Slide 58

Slide 58 text

Given: 
 Array> When: If any element of array is nil, then return nil Else, return array of unwrapped, non-nil elements Then: Optional>

Slide 59

Slide 59 text

func sequence(_ vs: [Validated]) -> Validated<[A], E> Future< Validated< Validated< Validated< Array, DeserializationError >, DeserializationError >, NetworkError > >

Slide 60

Slide 60 text

flatten A A Container> => Container

Slide 61

Slide 61 text

extension Validated { func flatten() -> Validated where A == Validated { ... } } Future< Validated< Validated< Array, DeserializationError >, NetworkError >>

Slide 62

Slide 62 text

extension Validated { func mapErrors(_ f: (E) -> F) -> Validated { ... } } // put errors into Either container Future< Validated< Validated< Array, Either >, Either >>

Slide 63

Slide 63 text

We’re left with 3 containers-deep nesting // after flattening again Future< // 1st level Validated< // 2nd level [Repo], // 3rd level Either > >

Slide 64

Slide 64 text

Filter Swift repos let repos: Future< Validated< Array, Either > > = githubClient.fetch(.repos, for: user) .map { deserialize($0) } .{ // transforms described before } repos.filter { }

Slide 65

Slide 65 text

No content

Slide 66

Slide 66 text

Container1> + (A) -> B = Container1> innerMap B A (A) -> B

Slide 67

Slide 67 text

Two ways of implementing: • protocol-based • method-based

Slide 68

Slide 68 text

Inverse of type erasure protocol Protocol { associatedtype A } Type erasure struct AnyProtocol 
 : Protocol struct Container “Type rasure” protocol ContainerType { associatedtype A }

Slide 69

Slide 69 text

1. Create protocol protocol ValidatedType { associatedtype PA associatedtype PE } extension Validated: ValidatedType { typealias PA = A typealias PE = E }

Slide 70

Slide 70 text

2. Duplicate API in protocol (return concrete type) protocol ValidatedType { associatedtype PA associatedtype PE func map(_ f: (PA) -> B) -> Validated } extension Validated: ValidatedType {}

Slide 71

Slide 71 text

3. Implement the nested method in a constrained extension extension Future where A: ValidatedType { func map( _ f: @escaping (A.PA) -> B ) -> Future> { return map { $0.map(f) } } }

Slide 72

Slide 72 text

Method-based 1. Generalize the method,
 not extension 2. Add constraints to 
 the method, not extension

Slide 73

Slide 73 text

1. Generalize the method, not extension extension Future { func map( _ f: @escaping (VA) -> B ) -> Future> { // work in progress } }

Slide 74

Slide 74 text

2. Add constraints to the method, not extension extension Future { func map( _ f: @escaping (VA) -> B ) -> Future> where A == Validated { return map { $0.map(f) } } }

Slide 75

Slide 75 text

!"

Slide 76

Slide 76 text

Now we can filter Swift repos! let repos: Future< Validated< Array, Either >> = githubClient.fetch(.repos, for: user) .map { deserialize($0) } .{ // transforms described before } repos.filter { (repo: Repo) -> Bool in repo.language == “Swift” } // it works!

Slide 77

Slide 77 text

No content

Slide 78

Slide 78 text

Use code generation Please see this great talk for details:
 Elviro Rocca — Protocol-Oriented Monad Transformers https://www.youtube.com/watch?v=Zmb86zblcto

Slide 79

Slide 79 text

Use “wide” containers, like Observable

Slide 80

Slide 80 text

Future< <== observable is async Validated< <== observable can return error Array< <== observable is sequence Repo >, Either > > Observable <- but some information will be lost!

Slide 81

Slide 81 text

No content

Slide 82

Slide 82 text

Thanks! Questions?