Utilizamos seu perfil e dados de atividades no LinkedIn para personalizar e exibir anúncios mais relevantes. Altere suas preferências de anúncios quando desejar.
Próximos SlideShares
Carregando em…5
×

# Functional Design Patterns (DevTernity 2018)

3.368 visualizações

(video and more at http://fsharpforfunandprofit.com/fppatterns)

In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID. The functional programming community has design patterns and principles as well. This talk will provide an overview of some of these patterns (such as currying, monads), and present some demonstrations of FP design in practice. We'll also look at some of the ways you can use these patterns as part of a domain driven design process, with some simple real world examples in F#. No jargon, no maths, and no prior F# experience necessary.

• Full Name
Comment goes here.

Are you sure you want to Yes No

### Functional Design Patterns (DevTernity 2018)

1. 1. Functional Design Patterns @ScottWlaschin fsharpforfunandprofit.com DevTernity 2018 Edition
2. 2. This talk A whirlwind tour of many sights Don't worry if you don't understand everything
3. 3. HOW I GOT HERE
4. 4. Me I've been programming a long time
5. 5. I used to be a normal programmer...
6. 6. And then I was introduced to some functional programmers…
7. 7. https://www.flickr.com/photos/37511372@N08/5488671752/ Haskell programmers F#/OCaml programmers Visual Basic programmers Lisp programmers
8. 8. Now I can say this with a straight face: “A monad is just a monoid in the category of endofunctors, what’s the problem?”
9. 9. FP DESIGN PATTERNS
10. 10. • Single Responsibility Principle • Open/Closed principle • Dependency Inversion Principle • Interface Segregation Principle • Factory pattern • Strategy pattern • Decorator pattern • Visitor pattern OO pattern/principle
11. 11. • Single Responsibility Principle • Open/Closed principle • Dependency Inversion Principle • Interface Segregation Principle • Factory pattern • Strategy pattern • Decorator pattern • Visitor pattern OO pattern/principle Borg response
12. 12. • Single Responsibility Principle • Open/Closed principle • Dependency Inversion Principle • Interface Segregation Principle • Factory pattern • Strategy pattern • Decorator pattern • Visitor pattern • Functions • Functions • Functions, also • Functions • You will be assimilated! • Functions again • Functions • Resistance is futile! OO pattern/principle FP equivalent Seriously, FP patterns are different
13. 13. Overview • 3 Core Principles of FP design • Pattern 1: Functions as parameters • Pattern 2: Composing multi-parameter functions • Pattern 3: "bind" • Pattern 4: "map" • Pattern 5: Monoids
14. 14. THREE CORE PRINCIPLES OF FUNCTIONAL PROGRAMMING There are more...
15. 15. Core principles of FP Function Types are not classes Functions are things Composition everywhere
16. 16. Core principle: Functions are things Function
17. 17. The Tunnel of Transformation Function apple -> banana A function is a standalone thing, not attached to a class
18. 18. let z = 1 1 let addOne x = x + 1 int-> int
19. 19. int->(int->int)int int->int Function as output
20. 20. intInt ->int Function as input (int->int)->int
21. 21. int int Function as parameterint->int int->int
22. 22. Core principle: Composition everywhere
23. 23. Function 1 apple -> banana Function 2 banana -> cherry
24. 24. >> Function 1 apple -> banana Function 2 banana -> cherry
25. 25. New Function apple -> cherry Can't tell it was built from smaller functions! Where did the banana go?
26. 26. Composition works at all scales
27. 27. Low-level operation ToUpper stringstring
28. 28. Low-level operation Service AddressValidator For those under 30... Validation Result Address Low-level operation Low-level operation a "service" is just like a microservice but without the "micro" in front
29. 29. Service Use-case UpdateProfileData ChangeProfile Result ChangeProfile Request Service Service
30. 30. Use-case Web application Http Response Http Request Use-case Use-case
31. 31. Core principle: Types are not classes So, what is a type then?
32. 32. Set of valid inputs Function
33. 33. Set of valid outputs Function
34. 34. Set of valid inputs Set of valid outputs Function A type is a just a name for a set of things
35. 35. Set of valid inputs Set of valid outputs Function 1 2 3 4 5 6 This is type "integer"
36. 36. Set of valid inputs Set of valid outputs Function This is type "string" "abc" "but" "cobol" "double" "end" "float"
37. 37. 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 GordonWood
38. 38. Set of valid inputs Set of valid outputs Function This is type "Fruit"
39. 39. Set of valid inputs Set of valid outputs Function This is a type of Fruit->Fruit functions
40. 40. Composition everywhere: Types can be composed too "Algebraic type system" "Composable type system"
41. 41. New types are built from smaller types by: Composing with “AND” Composing with “OR”
42. 42. Example: tuples, structs, records FruitSalad = One each of and and “AND” types (Record types) type FruitSalad = { Apple: AppleVariety Banana: BananaVariety Cherry: CherryVariety }
43. 43. Snack = or or “OR” types (Choice types) type Snack = | Apple of AppleVariety | Banana of BananaVariety | Cherry of CherryVariety
44. 44. Real world example of type composition
45. 45. Example of some requirements: We accept three forms of payment: Cash, Check, or Card. For Cash we don't need any extra information For Checks we need a check number For Cards we need a card type and card number
46. 46. interface IPaymentMethod {..} class Cash() : IPaymentMethod {..} class Check(int checkNo): IPaymentMethod {..} class Card(string cardType, string cardNo) : IPaymentMethod {..} In OOP you would probably implement it as an interface and a set of subclasses, like this:
47. 47. type CheckNumber = int type CardNumber = string In FP you would probably implement by composing types, like this:
48. 48. type CheckNumber = ... type CardNumber = … type CardType = Visa | Mastercard type CreditCardInfo = { CardType : CardType CardNumber : CardNumber }
49. 49. type CheckNumber = ... type CardNumber = ... type CardType = ... type CreditCardInfo = ... type PaymentMethod = | Cash | Check of CheckNumber | Card of CreditCardInfo
50. 50. type CheckNumber = ... type CardNumber = ... type CardType = ... type CreditCardInfo = ... type PaymentMethod = | Cash | Check of CheckNumber | Card of CreditCardInfo type PaymentAmount = decimal type Currency = EUR | USD
51. 51. type CheckNumber = ... type CardNumber = ... type CardType = ... type CreditCardInfo = ... type PaymentMethod = | Cash | Check of CheckNumber | Card of CreditCardInfo type PaymentAmount = decimal type Currency = EUR | USD type Payment = { Amount : PaymentAmount Currency: Currency Method: PaymentMethod }
52. 52. type CheckNumber = int type CardNumber = string type CardType = Visa | Mastercard type CreditCardInfo = CardType * CardNumber type PaymentMethod = | Cash | Check of CheckNumber | Card of CreditCardInfo type PaymentAmount = decimal type Currency = EUR | USD type Payment = { Amount : PaymentAmount Currency: Currency Method: PaymentMethod }
53. 53. Design principle: Use static types for domain modelling and documentation Static types only! Sorry Clojure and JS developers 
54. 54. A big topic and not enough time   More on DDD and designing with types at fsharpforfunandprofit.com/ddd
55. 55. PATTERN 1: FUNCTIONS AS PARAMETERS
56. 56. Guideline: Parameterize all the things
57. 57. let printList() = for i in [1..10] do printfn "the number is %i" i
58. 58. So parameterize the data let printList aList = for i in aList do printfn "the number is %i" i
59. 59. let printList aList = for i in aList do printfn "the number is %i" i
60. 60. let printList anAction aList = for i in aList do anAction i So parameterize the action as well: We've decoupled the behavior from the data. Any list, any action!
61. 61. C# parameterization example
62. 62. public static int Product(int n) { int product = 1; for (int i = 1; i <= n; i++) { product *= i; } return product; } public static int Sum(int n) { int sum = 0; for (int i = 1; i <= n; i++) { sum += i; } return sum; }
63. 63. public static int Product(int n) { int product = 1; for (int i = 1; i <= n; i++) { product *= i; } return product; } public static int Sum(int n) { int sum = 0; for (int i = 1; i <= n; i++) { sum += i; } return sum; }
64. 64. public static int Product(int n) { int product = 1; for (int i = 1; i <= n; i++) { product *= i; } return product; } public static int Sum(int n) { int sum = 0; for (int i = 1; i <= n; i++) { sum += i; } return sum; }
65. 65. After parameterization
66. 66. public static int Aggregate( int initialValue, Func<int,int,int> action, int n) { int totalSoFar = initialValue; for (int i = 1; i <= n; i++) { totalSoFar = action(totalSoFar,i); } return totalSoFar; }
67. 67. Tip: Function types are "interfaces"
68. 68. interface IBunchOfMethods { int DoSomething(int x); string DoSomethingElse(int x); void DoAThirdThing(string x); } Let's take the Single Responsibility Principle and the Interface Segregation Principle to the extreme... Every interface should have only one method!
69. 69. interface IBunchOfMethods { int DoSomething(int x); } An interface with one method is a just a function type type DoSomething: int -> int
70. 70. type DoSomething: int -> int *Any* function with that type is compatible with it let add2 x = x + 2 // int -> int let times3 x = x * 3 // int -> int No interface declaration needed!
71. 71. Example: Decorator pattern
72. 72. let isEven x = ... // int -> bool isEvenint bool Log the input Log the output
73. 73. let isEven x = ... // int -> bool isEvenint bool isEvenint boollogint int logbool bool Compose!
74. 74. let isEven x = ... // int -> bool isEvenint bool logint log boolisEven
75. 75. let isEven x = ... // int -> bool isEvenint bool int log bool let isEvenWithLogging = // int -> bool Substitutable for original isEven isEvenWithLogging
76. 76. Tip: "Use interfaces for loose coupling" Use function parameters for loose coupling
77. 77. PATTERN 2: COMPOSING MULTI-PARAMETER FUNCTIONS
78. 78. Bad news: Composition patterns only work for functions that have one parameter! 
79. 79. Good news! Every function can be turned into a one parameter function 
80. 80. let add x y = x + y let add = (fun x y -> x + y) let add x = (fun y -> x + y) int-> int->int int-> int->int int-> (int->int) Normal function (Two parameters)
81. 81. let add x y = x + y let add = (fun x y -> x + y) let add x = (fun y -> x + y) int-> int->int int-> int->int int-> (int->int)
82. 82. Pattern: Partial application
83. 83. let name = "Scott" printfn "Hello, my name is %s" name
84. 84. let name = "Scott" (printfn "Hello, my name is %s") name
85. 85. let hello = (printfn "Hello, my name is %s") Can reuse "hello" in many places now! let name = "Scott" hello name let name = "Alice" hello name
86. 86. Example: Partial application with lists
87. 87. let names = ["Alice"; "Bob"; "Scott"] List.iter hello names //foreach name in names let hello = printfn "Hello, my name is %s"
88. 88. let add1 = (+) 1 let equals2 = (=) 2 [1..100] |> List.map add1 |> List.filter equals2
89. 89. PATTERN 3 "BIND"
90. 90. Taming the "pyramid of doom"
91. 91. let example input = let x = doSomething input if x <> null then let y = doSomethingElse x if y <> null then let z = doAThirdThing y if z <> null then let result = z result else null else null else null I know you could do early returns, but bear with me...
93. 93. let example input = let x = doSomething input if x <> null then let y = doSomethingElse x if y <> null then let z = doAThirdThing y if z <> null then let result = z result else null else null else null Nulls are a code smell: replace with Option! Let's fix this!
94. 94. let example input = let x = doSomething input if x.IsSome then let y = doSomethingElse (x.Value) if y.IsSome then let z = doAThirdThing (y.Value) if z.IsSome then let result = z.Value Some result else None else None else None Much more elegant, yes? No! This is fugly! But there is a pattern we can exploit...
95. 95. let example input = let x = doSomething input if x.IsSome then let y = doSomethingElse (x.Value) if y.IsSome then let z = doAThirdThing (y.Value) if z.IsSome then // do something with z.Value // in this block else None else None else None
96. 96. let example input = let x = doSomething input if x.IsSome then let y = doSomethingElse (x.Value) if y.IsSome then // do something with y.Value // in this block else None else None
97. 97. let example input = let x = doSomething input if x.IsSome then // do something with x.Value // in this block else None Can you see the pattern?
98. 98. if opt.IsSome then //do something with opt.Value else None
99. 99. let ifSomeDo f opt = if opt.IsSome then f opt.Value else None
100. 100. let example input = doSomething input |> ifSomeDo doSomethingElse |> ifSomeDo doAThirdThing |> ifSomeDo ... let ifSomeDo f opt = if opt.IsSome then f opt.Value else None
101. 101. Some None Input -> This is an example of a more general problem
102. 102. on Some Bypass on None
103. 103. >> >> Composing one-track functions is fine...
104. 104. >> >> ... and composing two-track functions is fine...
105. 105.   ... but composing switches is not allowed!
106. 106. How to combine the mismatched functions?
107. 107. “Bind” is the answer! Bind all the things!
108. 108. Two-track input Two-track input One-track input Two-track input  
109. 109. Two-track input Slot for switch function Two-track output
110. 110. Two-track input Two-track output
111. 111. let bind nextFunction optionInput = match optionInput with | Some s -> nextFunction s | None -> None Two-track input Two-track output
112. 112. let bind nextFunction optionInput = match optionInput with | Some s -> nextFunction s | None -> None Two-track input Two-track output
113. 113. let bind nextFunction optionInput = match optionInput with | Some s -> nextFunction s | None -> None Two-track input Two-track output
114. 114. let bind nextFunction optionInput = match optionInput with | Some s -> nextFunction s | None -> None Two-track input Two-track output
115. 115. Pattern: Use bind to chain options
116. 116. let example input = let x = doSomething input if x.IsSome then let y = doSomethingElse (x.Value) if y.IsSome then let z = doAThirdThing (y.Value) if z.IsSome then let result = z.Value Some result else None else None else None Before
117. 117. let bind f opt = match opt with | Some v -> f v | None -> None After
118. 118. let example input = doSomething input |> bind doSomethingElse |> bind doAThirdThing |> bind ... let bind f opt = match opt with | Some v -> f v | None -> None No pyramids! Code is linear and clear. This pattern is called “monadic bind” After
119. 119. Pattern: Use bind to chain tasks a.k.a "promise" "future"
120. 120. When task completesWait Wait
123. 123. Pattern: Use bind to chain error handlers
124. 124. string UpdateCustomerWithErrorHandling() { var request = receiveRequest(); validateRequest(request); canonicalizeEmail(request); db.updateDbFromRequest(request); smtpServer.sendEmail(request.Email) return "OK"; }
125. 125. string UpdateCustomerWithErrorHandling() { var request = receiveRequest(); var isValidated = validateRequest(request); if (!isValidated) { return "Request is not valid" } canonicalizeEmail(request); db.updateDbFromRequest(request); smtpServer.sendEmail(request.Email) return "OK"; }
126. 126. string UpdateCustomerWithErrorHandling() { var request = receiveRequest(); var isValidated = validateRequest(request); if (!isValidated) { return "Request is not valid" } canonicalizeEmail(request); var result = db.updateDbFromRequest(request); if (!result) { return "Customer record not found" } smtpServer.sendEmail(request.Email) return "OK"; }
127. 127. string UpdateCustomerWithErrorHandling() { var request = receiveRequest(); var isValidated = validateRequest(request); if (!isValidated) { return "Request is not valid" } canonicalizeEmail(request); try { var result = db.updateDbFromRequest(request); if (!result) { return "Customer record not found" } } catch { return "DB error: Customer record not updated" } smtpServer.sendEmail(request.Email) return "OK"; }
128. 128. string UpdateCustomerWithErrorHandling() { var request = receiveRequest(); var isValidated = validateRequest(request); if (!isValidated) { return "Request is not valid" } canonicalizeEmail(request); try { var result = db.updateDbFromRequest(request); if (!result) { return "Customer record not found" } } catch { return "DB error: Customer record not updated" } if (!smtpServer.sendEmail(request.Email)) { log.Error "Customer email not sent" } return "OK"; }
129. 129. string UpdateCustomerWithErrorHandling() { var request = receiveRequest(); var isValidated = validateRequest(request); if (!isValidated) { return "Request is not valid" } canonicalizeEmail(request); try { var result = db.updateDbFromRequest(request); if (!result) { return "Customer record not found" } } catch { return "DB error: Customer record not updated" } if (!smtpServer.sendEmail(request.Email)) { log.Error "Customer email not sent" } return "OK"; }
130. 130. Tip: Use a Result type for error handling
131. 131. Request SuccessValidate Failure type Result = | Ok of SuccessValue | Error of ErrorValue Define a choice type
132. 132. Request SuccessValidate Failure let validateInput input = if input.name = "" then Error "Name must not be blank" else if input.email = "" then Error "Email must not be blank" else Ok input // happy path
133. 133. Validate UpdateDb SendEmail
134. 134. Validate UpdateDb SendEmail
135. 135. Functional flow without error handling let updateCustomer = receiveRequest() |> validateRequest |> canonicalizeEmail |> updateDbFromRequest |> sendEmail |> returnMessage Before One track
136. 136. let updateCustomerWithErrorHandling = receiveRequest() |> validateRequest |> canonicalizeEmail |> updateDbFromRequest |> sendEmail |> returnMessage Functional flow with error handling After Two track
137. 137. FP terminology • A monad is – A data type – With an associated bind/flatMap function (and some other stuff) – With a sensible implementation (monad laws). • A monadic function is – A switch/points function – bind/flatMap is used to compose them
138. 138. Tip: Monads are a general purpose way of composing functions with complex outputs
139. 139. PATTERN 4 "MAP"
140. 140. World of normal values int string bool World of options Option<int> Option<string> Option<bool>
141. 141. World of options World of normal values int string bool Option<int> Option<string> Option<bool> 
142. 142. World of options World of normal values Option<int> Option<string> Option<bool>  int string bool
143. 143. let add42 x = x + 42 add42 1 // 43
144. 144. let add42ToOption opt = if opt.IsSome then let newVal = add42 opt.Value Some newVal else None 
145. 145. World of options World of normal values add42 
146. 146. World of options World of normal values add42
147. 147. World of options World of normal values option -> -> option Option.map
149. 149. World of lists World of normal values List.map list-> -> list
151. 151. World of async World of normal values async<T> -> -> async<U> Async.map
152. 152. Guideline: Most wrapped generic types have a “map”. Use it!
153. 153. Guideline: If you create your own generic type, create a “map” for it.
154. 154. FP terminology • A functor is – A data type – With an associated "map" function (with a sensible implementation)
155. 155. PATTERN 5: MONOIDS
157. 157. 1 + 2 = 3 1 + (2 + 3) = (1 + 2) + 3 1 + 0 = 1 0 + 1 = 1
158. 158. 1 + 2 = 3 Some things A way of combining them
159. 159. 2 x 3 = 6 Some things A way of combining them
160. 160. "a" + "b" = "ab" Some things A way of combining them
161. 161. concat([a],[b]) = [a; b] Some things A way of combining them
162. 162. 1 + 2 1 + 2 + 3 1 + 2 + 3 + 4 Is an integer Is an integer A pairwise operation has become an operation that works on lists!
163. 163. 1 + (2 + 3) = (1 + 2) + 3 Order of combining doesn’t matter 1 + 2 + 3 + 4 (1 + 2) + (3 + 4) ((1 + 2) + 3) + 4 All the same
164. 164. 1 - (2 - 3) = (1 - 2) - 3 Order of combining does matter
165. 165. 1 + 0 = 1 0 + 1 = 1 A special kind of thing that when you combine it with something, just gives you back the original something
166. 166. 42 * 1 = 42 1 * 42 = 42 A special kind of thing that when you combine it with something, just gives you back the original something
167. 167. "" + "hello" = "hello" "hello" + "" = "hello" “Zero” for strings
168. 168. • You start with a bunch of things, and some way of combining them two at a time. • Rule 1 (Closure):The result of combining two things is always another one of the things. • Rule 2 (Associativity):When combining more than two things, which pairwise combination you do first doesn't matter. • Rule 3 (Identity element):There is a special thing called "zero" such that when you combine any thing with "zero" you get the original thing back. A monoid!
169. 169. • Rule 1 (Closure):The result of combining two things is always another one of the things. • Benefit: converts pairwise operations into operations that work on lists. 1 + 2 + 3 + 4 [ 1; 2; 3; 4 ] |> List.reduce (+) We'll see this a lot!
170. 170. 1 * 2 * 3 * 4 [ 1; 2; 3; 4 ] |> List.reduce (*) • Rule 1 (Closure):The result of combining two things is always another one of the things. • Benefit: converts pairwise operations into operations that work on lists.
171. 171. "a" + "b" + "c" + "d" [ "a"; "b"; "c"; "d" ] |> List.reduce (+) • Rule 1 (Closure):The result of combining two things is always another one of the things. • Benefit: converts pairwise operations into operations that work on lists.
172. 172. • Rule 2 (Associativity):When combining more than two things, which pairwise combination you do first doesn't matter. • Benefit: Divide and conquer, parallelization, and incremental accumulation.
173. 173. Parallelization: 1 + 2 + 3 + 4
174. 174. Parallelization: (1 + 2) (3 + 4) 3 + 7
175. 175. • Rule 2 (Associativity):When combining more than two things, which pairwise combination you do first doesn't matter. • Benefit: Divide and conquer, parallelization, and incremental accumulation.
176. 176. Incremental accumulation (1 + 2 + 3)
177. 177. Incremental accumulation (1 + 2 + 3) + 4
178. 178. Incremental accumulation (6) + 4
179. 179. • How can I use reduce on an empty list? • In a divide and conquer algorithm, what should I do if one of the "divide" steps has nothing in it? • When using an incremental algorithm, what value should I start with when I have no data?
180. 180. • Rule 3 (Identity element):There is a special thing called "zero" such that when you combine any thing with "zero" you get the original thing back. • Benefit: Initial value for empty or missing data
181. 181. Tip: Simplify aggregation code with monoids
182. 182. type OrderLine = {Qty:int; Total:float} let orderLines = [ {Qty=2; Total=19.98} {Qty=1; Total= 1.99} {Qty=3; Total= 3.99} ] How to add them up?
183. 183. type OrderLine = {Qty:int; Total:float} let addPair line1 line2 = let newQty = line1.Qty + line2.Qty let newTotal = line1.Total + line2.Total {Qty=newQty; Total=newTotal} orderLines |> List.reduce addPair // {Qty=6; Total= 25.96} Any combination of monoids is also a monoid Write a pairwise combiner Profit!
184. 184. Pattern: Convert non-monoids to monoids
185. 185. Customer + Customer + Customer Customer Stats + Customer Stats + Customer Stats Reduce Map Not a monoid A monoid Customer Stats (Total)