Slide 1

Slide 1 text

The Power Of Composition NDC Oslo 2020 @ScottWlaschin fsharpforfunandprofit.com

Slide 2

Slide 2 text

The Power Of Composition 1. The philosophy of composition 2. Ideas of functional programming – Functions and how to compose them – Types and how to compose them 3. Composition in practice – Roman Numerals – FizzBuzz gone functional – Uh oh, monads! – A web service

Slide 3

Slide 3 text

THE PHILOSOPHY OF COMPOSITION

Slide 4

Slide 4 text

Prerequisites for understanding composition • You must have been a child at some point • You must have played with Lego • You must have played with toy trains

Slide 5

Slide 5 text

Lego Philosophy

Slide 6

Slide 6 text

Lego Philosophy 1. All pieces are designed to be connected 2. The pieces are reusable in many contexts 3. Connect two pieces together and get another "piece" that can still be connected

Slide 7

Slide 7 text

All pieces are designed to be connected

Slide 8

Slide 8 text

The pieces are reusable in different contexts

Slide 9

Slide 9 text

Connect two pieces together and get another "piece" that can still be connected

Slide 10

Slide 10 text

Make big things from small things in the same way

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

Wooden Railway Track Philosophy 1. All pieces are designed to be connected 2. The pieces are reusable in many contexts 3. Connect two pieces together and get another "piece" that can still be connected

Slide 13

Slide 13 text

All pieces are designed to be connected

Slide 14

Slide 14 text

The pieces are reusable in different contexts

Slide 15

Slide 15 text

Connect two pieces together and get another "piece" that can still be connected You can keep adding and adding.

Slide 16

Slide 16 text

Make big things from small things in the same way

Slide 17

Slide 17 text

If you understand Lego and wooden railways, then you know everything about composition!

Slide 18

Slide 18 text

THE IDEAS OF FUNCTIONAL PROGRAMMING

Slide 19

Slide 19 text

Four ideas behind FP Function 3. Types are not classes 1. Functions are things 2. Build bigger functions using composition 4. Build bigger types using composition

Slide 20

Slide 20 text

FP idea #1: Functions are things Function

Slide 21

Slide 21 text

The Tunnel of Transformation Function apple -> banana A function is a thing which transforms inputs to outputs

Slide 22

Slide 22 text

A function is a standalone thing, not attached to a class

Slide 23

Slide 23 text

A function is a standalone thing, not attached to a class It can be used for inputs and outputs of other functions

Slide 24

Slide 24 text

A function can be an output thing input

Slide 25

Slide 25 text

output A function can be an input thing

Slide 26

Slide 26 text

input output A function can be a parameter

Slide 27

Slide 27 text

input output input output

Slide 28

Slide 28 text

FP idea #2: Build bigger functions using composition

Slide 29

Slide 29 text

Function 1 apple -> banana Function 2 banana -> cherry

Slide 30

Slide 30 text

>> Function 1 apple -> banana Function 2 banana -> cherry

Slide 31

Slide 31 text

New Function apple -> cherry Can't tell it was built from smaller functions! Where did the banana go?

Slide 32

Slide 32 text

Function composition in F# and C# using the "piping" approach

Slide 33

Slide 33 text

int add1(int x) => x + 1; int times2(int x) => x * 2; int square(int x) => x * x; add1(5); // = 6 times2(add1(5)); // = 12 square(times2(add1(5))); // = 144 Nested function calls can be confusing if too deep

Slide 34

Slide 34 text

add1 5 6 times2 12 square 144

Slide 35

Slide 35 text

5 |> add1 // = 6 5 |> add1 |> times2 // = 12 5 |> add1 |> times2 |> square // = 144 add1 times2 square 5 6 12 144 F# example

Slide 36

Slide 36 text

add1 times2 square 5 6 12 144 5.Pipe(add1); 5.Pipe(add1).Pipe(times2); 5.Pipe(add1).Pipe(times2).Pipe(square); C# example

Slide 37

Slide 37 text

Building big things from functions It's compositions all the way up

Slide 38

Slide 38 text

Low-level operation ToUpper string string

Slide 39

Slide 39 text

Low-level operation Service AddressValidator A “Service” is just like a microservice but without the "micro" in front Validation Result Address Low-level operation Low-level operation

Slide 40

Slide 40 text

Service Use-case UpdateProfileData ChangeProfile Result ChangeProfile Request Service Service

Slide 41

Slide 41 text

Use-case Web application Http Response Http Request Use-case Use-case

Slide 42

Slide 42 text

Http Response Http Request Even for complex applications, data flows only in one direction

Slide 43

Slide 43 text

No content

Slide 44

Slide 44 text

No content

Slide 45

Slide 45 text

FP idea #3: Types are not classes

Slide 46

Slide 46 text

So, what is a type then? A type is a just a name for a set of things Set of valid inputs Set of valid outputs Function

Slide 47

Slide 47 text

Set of valid inputs Set of valid outputs Function 1 2 3 4 5 6 This is type "integer" A type is a just a name for a set of things

Slide 48

Slide 48 text

Set of valid inputs Set of valid outputs Function This is type "string" "abc" "but" "cobol" "double" "end" "float" A type is a just a name for a set of things

Slide 49

Slide 49 text

Set of valid inputs Set of valid outputs Function This is type "Person" Donna Roy Javier Mendoza Nathan Logan Shawna Ingram Abel Ortiz Lena Robbins Gordon Wood A type is a just a name for a set of things

Slide 50

Slide 50 text

Set of valid inputs Set of valid outputs Function This is type "Fruit" A type is a just a name for a set of things

Slide 51

Slide 51 text

Set of valid inputs Set of valid outputs Function This is a type of Fruit->Fruit functions A type is a just a name for a set of things

Slide 52

Slide 52 text

FP idea #4: Types can be composed too

Slide 53

Slide 53 text

Algebraic type system

Slide 54

Slide 54 text

Bigger types are built from smaller types by: Composing with “AND” Composing with “OR”

Slide 55

Slide 55 text

FruitSalad = AND AND Compose with “AND”

Slide 56

Slide 56 text

Compose with “AND” enum AppleVariety { Red, Green } enum BananaVariety { Yellow, Brown } enum CherryVariety { Tart, Sweet } struct FruitSalad { AppleVariety Apple; BananaVariety Banana; CherryVariety Cherry; } C# example Apple AND Banana AND Cherry

Slide 57

Slide 57 text

Compose with “AND” type AppleVariety = Red | Green type BananaVariety = Yellow | Brown type CherryVariety = Tart | Sweet type FruitSalad = { Apple: AppleVariety Banana: BananaVariety Cherry: CherryVariety } F# example

Slide 58

Slide 58 text

Snack = OR OR Compose with “OR” type Snack = | Apple of AppleVariety | Banana of BananaVariety | Cherry of CherryVariety

Slide 59

Slide 59 text

A real world example of composing types

Slide 60

Slide 60 text

Some requirements: We accept three forms of payment: Cash, Paypal, or CreditCard. For Cash we don't need any extra information For Paypal we need an email address For Cards we need a card type and card number

Slide 61

Slide 61 text

interface IPaymentMethod {..} class Cash() : IPaymentMethod {..} class Paypal(string emailAddress): IPaymentMethod {..} class Card(string cardType, string cardNo) : IPaymentMethod {..} In OO design you would probably implement it as an interface and a set of subclasses, like this:

Slide 62

Slide 62 text

type EmailAddress = string type CardNumber = string In F# you would probably implement by composing types, like this:

Slide 63

Slide 63 text

type EmailAddress = ... type CardNumber = … type CardType = Visa | Mastercard type CreditCardInfo = { CardType : CardType CardNumber : CardNumber }

Slide 64

Slide 64 text

type EmailAddress = ... type CardNumber = ... type CardType = ... type CreditCardInfo = ... type PaymentMethod = | Cash | PayPal of EmailAddress | Card of CreditCardInfo

Slide 65

Slide 65 text

type EmailAddress = ... type CardNumber = ... type CardType = ... type CreditCardInfo = ... type PaymentMethod = | Cash | PayPal of EmailAddress | Card of CreditCardInfo type PaymentAmount = decimal type Currency = EUR | USD | RUB

Slide 66

Slide 66 text

type EmailAddress = ... type CardNumber = ... type CardType = ... type CreditCardInfo = ... type PaymentMethod = | Cash | PayPal of EmailAddress | Card of CreditCardInfo type PaymentAmount = decimal type Currency = EUR | USD | RUB type Payment = { Amount : PaymentAmount Currency : Currency Method : PaymentMethod }

Slide 67

Slide 67 text

type EmailAddress = ... type CardNumber = ... type CardType = ... type CreditCardInfo = ... type PaymentMethod = | Cash | PayPal of EmailAddress | Card of CreditCardInfo type PaymentAmount = decimal type Currency = EUR | USD | RUB type Payment = { Amount : PaymentAmount Currency : Currency Method : PaymentMethod }

Slide 68

Slide 68 text

No content

Slide 69

Slide 69 text

Composable types can be used as executable documentation

Slide 70

Slide 70 text

type Deal = Deck -> (Deck * Card) type PickupCard = (Hand * Card) -> Hand type Suit = Club | Diamond | Spade | Heart type Rank = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace type Card = { Suit:Suit; Rank:Rank } type Hand = Card list type Deck = Card list type Player = {Name:string; Hand:Hand} type Game = { Deck:Deck; Players:Player list } The domain on one screen!

Slide 71

Slide 71 text

type CardType = Visa | Mastercard type CardNumber = string type EmailAddress = string type PaymentMethod = | Cash | PayPal of EmailAddress | Card of CreditCardInfo | Bitcoin of BitcoinAddress

Slide 72

Slide 72 text

A big topic and not enough time   More on DDD and designing with types at fsharpforfunandprofit.com/ddd

Slide 73

Slide 73 text

Composition in practice: Time for some real examples!

Slide 74

Slide 74 text

COMPOSITION WITH PIPING (ROMAN NUMERALS) Technique #1

Slide 75

Slide 75 text

To Roman Numerals • Task: How to convert an arabic integer to roman numerals? • 5 => "V" • 12 => "XII" • 107 => "CVII"

Slide 76

Slide 76 text

To Roman Numerals

Slide 77

Slide 77 text

To Roman Numerals • Use the "tally" approach – Start with N copies of "I" – Replace five "I"s with a "V" – Replace two "V"s with a "X" – Replace five "X"s with a "L" – Replace two "L"s with a "C" – etc

Slide 78

Slide 78 text

To Roman Numerals number etc Replicate "I" Replace_IIIII_V Replace_VV_X Replace_XXXXX_L

Slide 79

Slide 79 text

string ToRomanNumerals(int number) { // define a helper function for each step string replace_IIIII_V(string s) => s.Replace("IIIII", "V"); string replace_VV_X(string s) => s.Replace("VV", "X"); string replace_XXXXX_L(string s) => s.Replace("XXXXX", "L"); string replace_LL_C(string s) => s.Replace("LL", "C"); // then combine them using piping return new string('I', number) .Pipe(replace_IIIII_V) .Pipe(replace_VV_X) .Pipe(replace_XXXXX_L) .Pipe(replace_LL_C); } C# example

Slide 80

Slide 80 text

let toRomanNumerals number = // define a helper function for each step let replace_IIIII_V str = replace "IIIII" "V" str let replace_VV_X str = replace "VV" "X" str let replace_XXXXX_L str = replace "XXXXX" "L" str let replace_LL_C str = replace "LL" "C" str // then combine them using piping String.replicate number "I" |> replace_IIIII_V |> replace_VV_X |> replace_XXXXX_L |> replace_LL_C F# example

Slide 81

Slide 81 text

IT'S NOT ALWAYS THIS EASY…

Slide 82

Slide 82 text

function A function B Compose

Slide 83

Slide 83 text

function A function B

Slide 84

Slide 84 text

function A and B  Easy!

Slide 85

Slide 85 text

... But here is a challenge

Slide 86

Slide 86 text

function A Input Output function B Input 1 Output Input 2

Slide 87

Slide 87 text

function A Input Output function B Input 1 Output Input 2 Challenge #1: How can we compose these? 

Slide 88

Slide 88 text

COMPOSITION WITH CURRYING (ROMAN NUMERALS) Technique #2

Slide 89

Slide 89 text

The Replace function oldValue outputString newValue inputString Replace

Slide 90

Slide 90 text

Uh-oh! Composition problem Replace I / V Replace V / X Replace X / L  

Slide 91

Slide 91 text

Bad news: Composition patterns only work for functions that have one parameter! 

Slide 92

Slide 92 text

Good news! Every function can be turned into a one parameter function 

Slide 93

Slide 93 text

Haskell Curry We named this technique after him

Slide 94

Slide 94 text

Input A Uncurried Function Input B Output C Curried Function Input A Intermediate Function Output C Input B What is currying? after currying Function as output

Slide 95

Slide 95 text

Input A Uncurried Function Input B Output C Curried Function Input A Intermediate Function Output C Input B What is currying? One input One input Currying means that *every* function can be converted to a series of one input functions

Slide 96

Slide 96 text

Replace Before currying input.Replace(oldValue, newValue); string output

Slide 97

Slide 97 text

Replace Old New Old New After currying Func replace(string oldVal, string newVal) => input => input.Replace(oldVal, newVal);

Slide 98

Slide 98 text

Replace Old New Old New After currying Func replace(string oldVal, string newVal) => input => input.Replace(oldVal, newVal);

Slide 99

Slide 99 text

Func replace(string oldVal, string newVal) => input => input.Replace(oldVal, newVal); Replace Old New Old New After currying This lambda (function) is returned one-parameter function

Slide 100

Slide 100 text

string ToRomanNumerals(int number) { // define a general helper function Func replace( string oldValue, string newValue) => input => input.Replace(oldValue, newValue); // then use piping return new string('I', number) .Pipe(replace("IIIII","V")) .Pipe(replace("VV","X")) .Pipe(replace("XXXXX","L")) .Pipe(replace("LL","C")); } C# example

Slide 101

Slide 101 text

string ToRomanNumerals(int number) { // define a general helper function Func replace( string oldValue, string newValue) => input => input.Replace(oldValue, newValue); // then use piping return new string('I', number) .Pipe(replace("IIIII","V")) .Pipe(replace("VV","X")) .Pipe(replace("XXXXX","L")) .Pipe(replace("LL","C")); } C# example

Slide 102

Slide 102 text

string ToRomanNumerals(int number) { // define a general helper function Func replace( string oldValue, string newValue) => input => input.Replace(oldValue, newValue); // then use piping return new string('I', number) .Pipe(replace("IIIII","V")) .Pipe(replace("VV","X")) .Pipe(replace("XXXXX","L")) .Pipe(replace("LL","C")); } C# example Only 2 of the 3 parameters are passed in The other parameter comes from the pipeline

Slide 103

Slide 103 text

let toRomanNumerals number = // no helper function needed. // currying occurs automatically in F# // combine using piping String.replicate number "I" |> replace "IIIII" "V" |> replace "VV" "X" |> replace "XXXXX" "L" |> replace "LL" "C" F# example

Slide 104

Slide 104 text

let toRomanNumerals number = // no helper function needed. // currying occurs automatically in F# // combine using piping String.replicate number "I" |> replace "IIIII" "V" |> replace "VV" "X" |> replace "XXXXX" "L" |> replace "LL" "C" Only 2 of the 3 parameters are passed in F# example The other parameter comes from the pipeline

Slide 105

Slide 105 text

Partial Application

Slide 106

Slide 106 text

Partial Application let add x y = x + y let multiply x y = x * y 5 |> add 2 |> multiply 3 Piping provides the missing argument partial application

Slide 107

Slide 107 text

Partial Application Replace ReplaceOldNew Old New Old New String.replicate number "I" |> replace "IIIII" "V" |> replace "VV" "X" |> replace "XXXXX" "L" |> replace "LL" "C" Only 2 parameters passed in Piping provides the missing argument

Slide 108

Slide 108 text

Pipelines are extensible

Slide 109

Slide 109 text

let toRomanNumerals number = String.replicate number "I" |> replace "IIIII" "V" |> replace "VV" "X" |> replace "XXXXX" "L" |> replace "LL" "C" Composable => extensible // can easily add new segments to the pipeline |> replace "VIIII" "IX" |> replace "IIII" "IV" |> replace "LXXXX" "XC"

Slide 110

Slide 110 text

function Input Output function Input 1 Output Input 2 Challenge #1: How can we compose these? 

Slide 111

Slide 111 text

Here is another challenge

Slide 112

Slide 112 text

function A Input Output function B Input Output 1 Output 2

Slide 113

Slide 113 text

function A Input Output function B Input Output 1 Output 2 Challenge #2: How can we compose these? 

Slide 114

Slide 114 text

COMPOSITION WITH BIND (FIZZBUZZ) Technique #3

Slide 115

Slide 115 text

FizzBuzz definition Write a program that takes a number as input • For multiples of three print "Fizz" • For multiples of five print "Buzz" • For multiples of both three and five print "FizzBuzz" • Otherwise, print the original number

Slide 116

Slide 116 text

let fizzBuzz n = if (isDivisibleBy n 15) then printfn "FizzBuzz" else if (isDivisibleBy n 3) then printfn "Fizz" else if (isDivisibleBy n 5) then printfn "Buzz" else printfn "%i" n let isDivisibleBy n divisor = (n % divisor) = 0 // helper function A simple F# implementation

Slide 117

Slide 117 text

let fizzBuzz n = if (isDivisibleBy n 15) then printfn "FizzBuzz" else if (isDivisibleBy n 3) then printfn "Fizz" else if (isDivisibleBy n 5) then printfn "Buzz" else printfn "%i" n let isDivisibleBy n divisor = (n % divisor) = 0 // helper function A simple F# implementation

Slide 118

Slide 118 text

Pipeline implementation number Handle 15 case

Slide 119

Slide 119 text

Pipeline implementation Handle 3 case number Handle 15 case

Slide 120

Slide 120 text

Pipeline implementation Handle 3 case Handle 5 case number Handle 15 case

Slide 121

Slide 121 text

Pipeline implementation Handle 3 case Handle 5 case number Answer Handle 15 case Last step

Slide 122

Slide 122 text

number Handle case Handled (e.g. "Fizz", "Buzz") Unhandled (e.g. 2, 7, 13)

Slide 123

Slide 123 text

Unhandled Handled Input -> or

Slide 124

Slide 124 text

Unhandled Handled Input -> type FizzBuzzResult = | Unhandled of int // the original int | Handled of string // "Fizz", Buzz", etc Idea from http://weblog.raganwald.com/2007/01/dont-overthink-fizzbuzz.html or

Slide 125

Slide 125 text

type FizzBuzzResult = | Unhandled of int // the original int | Handled of string // "Fizz", Buzz", etc let handle divisor label n = if (isDivisibleBy n divisor) then Handled label else Unhandled n Idea from http://weblog.raganwald.com/2007/01/dont-overthink-fizzbuzz.html

Slide 126

Slide 126 text

type FizzBuzzResult = | Unhandled of int // the original int | Handled of string // "Fizz", Buzz", etc let handle divisor label n = if (isDivisibleBy n divisor) then Handled label else Unhandled n

Slide 127

Slide 127 text

12 |> handle 3 "Fizz" // Handled "Fizz" 10 |> handle 3 "Fizz" // Unhandled 10 10 |> handle 5 "Buzz" // Handled "Buzz" handle 5 "Buzz"

Slide 128

Slide 128 text

let fizzbuzz n = let result15 = n |> handle 15 "FizzBuzz" match result15 with | Handled str -> str | Unhandled n -> let result3 = n |> handle 3 "Fizz" match result3 with | Handled str -> str | Unhandled n -> let result5 = n |> handle 5 "Buzz" match result5 with | Handled str -> str | Unhandled n -> string n // convert to string First implementation attempt

Slide 129

Slide 129 text

let fizzbuzz n = let result15 = n |> handle 15 "FizzBuzz" match result15 with | Handled str -> str | Unhandled n -> let result3 = n |> handle 3 "Fizz" match result3 with | Handled str -> str | Unhandled n -> let result5 = n |> handle 5 "Buzz" match result5 with | Handled str -> str | Unhandled n -> // do something with Unhandled value

Slide 130

Slide 130 text

let fizzbuzz n = let result15 = n |> handle 15 "FizzBuzz" match result15 with | Handled str -> str | Unhandled n -> let result3 = n |> handle 3 "Fizz" match result3 with | Handled str -> str | Unhandled n -> // do something with Unhandled value // ... // ...

Slide 131

Slide 131 text

let fizzbuzz n = let result15 = n |> handle 15 "FizzBuzz" match result15 with | Handled str -> str | Unhandled n -> // do something with Unhandled value // ... // ...

Slide 132

Slide 132 text

if Handled then // return the string if Unhandled then // do something with the number

Slide 133

Slide 133 text

If Unhandled If Handled Bypass and return the string

Slide 134

Slide 134 text

let ifUnhandledDo f result = match result with | Handled str -> Handled str | Unhandled n -> f n

Slide 135

Slide 135 text

let fizzbuzz n = n |> handle 15 "FizzBuzz" |> ifUnhandledDo (handle 3 "Fizz") |> ifUnhandledDo (handle 5 "Buzz") |> lastStep

Slide 136

Slide 136 text

let fizzbuzz n = n |> handle 15 "FizzBuzz" |> ifUnhandledDo (handle 3 "Fizz") |> ifUnhandledDo (handle 5 "Buzz") |> lastStep

Slide 137

Slide 137 text

let fizzbuzz n = n |> handle 15 "FizzBuzz" |> ifUnhandledDo (handle 3 "Fizz") |> ifUnhandledDo (handle 5 "Buzz") |> lastStep

Slide 138

Slide 138 text

let fizzbuzz n = n |> handle 15 "FizzBuzz" |> ifUnhandledDo (handle 3 "Fizz") |> ifUnhandledDo (handle 5 "Buzz") |> lastStep

Slide 139

Slide 139 text

let fizzbuzz n = n |> handle 15 "FizzBuzz" |> ifUnhandledDo (handle 3 "Fizz") |> ifUnhandledDo (handle 5 "Buzz") |> lastStep let lastStep result = match result with | Handled str -> str | Unhandled n -> string(n) // convert to string

Slide 140

Slide 140 text

let fizzbuzz n = n |> handle 15 "FizzBuzz" |> ifUnhandledDo (handle 3 "Fizz") |> ifUnhandledDo (handle 5 "Buzz") |> lastStep Composable => easy to extend

Slide 141

Slide 141 text

let fizzbuzz n = n |> handle 15 "FizzBuzz" |> ifUnhandledDo (handle 3 "Fizz") |> ifUnhandledDo (handle 5 "Buzz") |> ifUnhandledDo (handle 7 "Baz") |> lastStep Composable => easy to extend

Slide 142

Slide 142 text

let fizzbuzz n = n |> handle 15 "FizzBuzz" |> ifUnhandledDo (handle 3 "Fizz") |> ifUnhandledDo (handle 5 "Buzz") |> ifUnhandledDo (handle 7 "Baz") |> ifUnhandledDo (handle 11 "Pozz") |> lastStep Composable => easy to extend

Slide 143

Slide 143 text

let fizzbuzz n = n |> handle 15 "FizzBuzz" |> ifUnhandledDo (handle 3 "Fizz") |> ifUnhandledDo (handle 5 "Buzz") |> ifUnhandledDo (handle 7 "Baz") |> ifUnhandledDo (handle 11 "Pozz") |> ifUnhandledDo (handle 13 "Tazz") |> lastStep Composable => easy to extend

Slide 144

Slide 144 text

Another example: Chaining tasks

Slide 145

Slide 145 text

When task completes Wait Wait a.k.a "promise", "future"

Slide 146

Slide 146 text

let taskExample input = let taskX = startTask input taskX.WhenFinished (fun x -> let taskY = startAnotherTask x taskY.WhenFinished (fun y -> let taskZ = startThirdTask y taskZ.WhenFinished (fun z -> etc

Slide 147

Slide 147 text

let taskExample input = let taskX = startTask input taskX.WhenFinished (fun x -> let taskY = startAnotherTask x taskY.WhenFinished (fun y -> let taskZ = startThirdTask y taskZ.WhenFinished (fun z -> do something

Slide 148

Slide 148 text

let taskExample input = let taskX = startTask input taskX.WhenFinished (fun x -> let taskY = startAnotherTask x taskY.WhenFinished (fun y -> do something

Slide 149

Slide 149 text

let taskExample input = let taskX = startTask input taskX.WhenFinished (fun x -> do something

Slide 150

Slide 150 text

let whenFinishedDo f task = task.WhenFinished (fun taskResult -> f taskResult) let taskExample input = startTask input |> whenFinishedDo startAnotherTask |> whenFinishedDo startThirdTask |> whenFinishedDo ... Parameterize the next step

Slide 151

Slide 151 text

MONADS!

Slide 152

Slide 152 text

Is there a general solution to handling functions like this?

Slide 153

Slide 153 text

Yes! “Bind” is the answer! Bind all the things!

Slide 154

Slide 154 text

How do we compose these?

Slide 155

Slide 155 text

No content

Slide 156

Slide 156 text

>> >> Composing one-track functions is fine...

Slide 157

Slide 157 text

>> >> ... and composing two-track functions is fine...

Slide 158

Slide 158 text

  ... but composing points/switches is not allowed!

Slide 159

Slide 159 text

Two-track input Two-track output One-track input Two-track output  

Slide 160

Slide 160 text

Two-track input Two-track output

Slide 161

Slide 161 text

Two-track input Two-track output A function transformer

Slide 162

Slide 162 text

let bind nextFunction result = match result with | Unhandled n -> nextFunction n | Handled str -> Handled str Two-track input Two-track output

Slide 163

Slide 163 text

let bind nextFunction result = match result with | Unhandled n -> nextFunction n | Handled str -> Handled str Two-track input Two-track output

Slide 164

Slide 164 text

let bind nextFunction result = match result with | Unhandled n -> nextFunction n | Handled str -> Handled str Two-track input Two-track output

Slide 165

Slide 165 text

let bind nextFunction result = match result with | Unhandled n -> nextFunction n | Handled str -> Handled str Two-track input Two-track output

Slide 166

Slide 166 text

let bind nextFunction result = match result with | Unhandled n -> nextFunction n | Handled str -> Handled str Two-track input Two-track output

Slide 167

Slide 167 text

FP terminology • A monad is – A data type – With an associated "bind" function – (and some other stuff) • A monadic function is – A switch/points function – "bind" is used to compose them type FizzBuzzResult = | Unhandled of int | Handled of string

Slide 168

Slide 168 text

function A Input Output function B Input Output 1 Output 2 Challenge #2: How can we compose these? 

Slide 169

Slide 169 text

KLEISLI COMPOSITION (WEB SERVICE) Technique #4

Slide 170

Slide 170 text

compose with Kleisli Composition

Slide 171

Slide 171 text

Kleisli Composition

Slide 172

Slide 172 text

Kleisli Composition

Slide 173

Slide 173 text

Kleisli Composition

Slide 174

Slide 174 text

= compose with The result is the same kind of thing Kleisli Composition

Slide 175

Slide 175 text

The "Lego" approach to building a web server

Slide 176

Slide 176 text

Async HttpContext A HttpHandler "WebPart"

Slide 177

Slide 177 text

Async HttpContext A HttpHandler "WebPart"

Slide 178

Slide 178 text

= >=> The result is another HttpHandler so you can keep adding and adding Composition of HttpHandlers Kleisli composition symbol

Slide 179

Slide 179 text

path "/hello" Checks request path (might fail) matches path doesn't match

Slide 180

Slide 180 text

OK "Hello" Sets response 200 OK

Slide 181

Slide 181 text

path "/hello" >=> OK "Hello" Checks request path (might fail) Sets response >=> A new WebPart

Slide 182

Slide 182 text

choose [ ] Picks first HttpHandler that succeeds

Slide 183

Slide 183 text

choose [ path "/hello" >=> OK "Hello" path "/goodbye" >=> OK "Goodbye" ] Pick first path that succeeds

Slide 184

Slide 184 text

GET Only succeeds if request is a GET

Slide 185

Slide 185 text

GET >=> choose [ path "/hello" >=> OK "Hello" path "/goodbye" >=> OK "Goodbye" ]

Slide 186

Slide 186 text

let app = choose [ ] startWebServer defaultConfig app A complete web app GET >=> choose [ path "/hello" >=> OK "Hello" path "/goodbye" >=> OK "Goodbye" ] POST >=> choose [ path "/hello" >=> OK "Hello POST" path "/goodbye" >=> OK "Goodbye POST" ]

Slide 187

Slide 187 text

Http Response Http Request No classes, no inheritance, one-directional data flow!

Slide 188

Slide 188 text

Review • The philosophy of composition – Connectable, reusable parts – Building bigger things from smaller things • FP principles: – Composable functions – Composable types

Slide 189

Slide 189 text

Review A taste of various composition techniques: – Piping with "|>" – Currying/partial application – Composition using "bind" (monads!) – Kleisli composition using ">=>" Don't worry about understanding it all, but hopefully it's not so scary now!

Slide 190

Slide 190 text

Why bother? Benefits of composition: • Reusable parts – no strings attached • Testable – parts can be tested in isolation • Understandable – data flows in one direction • Maintainable – all dependencies are explicit • Extendable – can add new parts without touching old code • A different way of thinking – it's good for your brain to learn new things!

Slide 191

Slide 191 text

Slides and video here fsharpforfunandprofit.com/composition Thank you! @ScottWlaschin Me on twitter My book