SlideShare a Scribd company logo
Functional Programming for Production Quality Code 
Jack Fox 
jackfoxy.com  craftyThoughts 
@foxyjackfox 
Slides 
http://www.slideshare.net/jackfoxy 
Sample Code 
https://github.com/jackfoxy/Svcc2014Demo
Functional Programming for Production Quality Code 
o Success / Failure passing 
o Partial Application 
o Types, Summation Type, Generic Types 
o Pattern Matching 
o Modadic Bind 
o Function Composition 
o Units of Measure (design time types) 
o Computation Expressions 
o Typing your way into relational data
Ever seen this code? 
if condition1 then 
doThis() 
if condition2 then 
doThat() 
if condition3 then 
doSomeOtherThing() 
if condition3 then 
aTask() 
if condition4 then 
anotherTask() 
if condition5 then 
yetAnotherTask() 
if condition5 then 
finallyDone() 
else handleError() 
else handleError() 
else handleError() 
else handleError() 
else handleError() 
else handleError() 
else handleError()
Functional Programming 
Remember functions from high school math? 
f(x) = y 
one input 
parameter 
always maps 
to the same output
Functional Programming 
Remember functions from high school math? 
f(x) = y 
one input 
parameter 
always maps 
to the same output 
But I need multiple input parameters!
A compiler FP trick called “currying” 
let f x y z = 
let w = 1 
… //do something 
w //return 
f(x g(y h(z))) = w 
wrapping single 
parameter functions 
within functions 
f: x -> (y -> (z -> w)) 
function signature
o You don’t really need to know currying 
o Instead understand the inverse of currying 
o Unwrap the parameters of a function 
o Unwrapping is called “Partial Application”
Partial application 
o If this is a function 
let steamJob temperature barrelsOfSteam wellsToSteam = 
… 
somethingWeReturn 
steamJob : temperature: int -> barrelsOfSteam: int -> wellsToSteam: WellState list -> int 
o Then so is this 
let mySteamJob = steamJob 500 10000 
mySteamJob : (WellState list -> int)
Next: a short digression into types 
These are all types 
o int 
o string 
o list 
o WellState 
o Exception
Summation type 
o This is a type that takes the form of multiple types 
o It can only be one of those types at a time 
o In F# this type is called “discriminated union” 
type Choice<'T1, 'T2> = 
| Success of 'T1 
| Failure of 'T2 
note this in not the actual 
Choice type in Fsharp.Core
Generic types 
generic types in 
type constructor 
type Choice<'T1, 'T2> = 
| Success of 'T1 
| Failure of 'T2
Return Summation Type 
(Discriminated Union) 
let steamJob2 (temperature :int) (barrelsOfSteam : int) (wellsToSteam : WellState list) = 
… 
if … then 
Success wellsToSteam 
else 
Failure (BadSteamJob 
(sprintf "BadSteamJob temperature %i barrelsOfSteam %i wellsToSteam %A“ 
temperature barrelsOfSteam wellsToSteam) :> Exception )
Return Summation Type 
(Discriminated Union) 
let steamJob2 (temperature :int) (barrelsOfSteam : int) (wellsToSteam : WellState list) = 
… 
if … then 
Success wellsToSteam 
else 
Failure (BadSteamJob 
(sprintf "BadSteamJob temperature %i barrelsOfSteam %i wellsToSteam %A“ 
temperature barrelsOfSteam wellsToSteam) :> Exception ) 
steamJob : temperature:int -> barrelsOfSteam:int -> wellsToSteam:WellState list -> 
Choice<WellState list, Exception> 
generic constructor types 
replaced with real types
let result = steamJob2 500 4000 wellsToSteam 
match result with 
| Success steamedWells -> printfn "%A" steamedWells 
| Failure exn -> printfn "%s" exn.Message 
steamJob : temperature:int -> barrelsOfSteam:int -> wellsToSteam:WellState list -> 
Choice<WellState list, Exception> 
Consuming a Summation Type 
(Discriminated Union)
The tools to pipeline a production process 
o Partial application 
o Summation type / Coproduct type / Discriminated Union (F#) 
o Pattern matching 
o Generic types
The tools to pipeline a production process 
o Partial application 
o Summation type / Coproduct type / Discriminated Union (F#) 
o Pattern matching 
o Generic types 
o Monadic Bind
Monadic Bind 
let bind nextFunction lastOutput = 
match lastOutput with 
| Success s -> nextFunction s 
| Failure f -> Failure f 
bind : nextFunction : ('a -> Choice<'b,'c>) -> lastOutput : Choice<'a,'c> -> Choice<'b,'c> 
generic constructor types to 
be replaced with real types
Monadic Bind 
let bind nextFunction lastOutput = 
match lastOutput with 
| Success s -> nextFunction s 
| Failure f -> Failure f 
the generics line up between nextFunction and lastOutput 
bind : nextFunction:('a -> Choice<'b,'c>) -> lastOutput:Choice<'a,'c> -> Choice<'b,'c> 
resulting output lets us chain indefinitely
The tools to pipeline a production process 
o Partial application 
o Summation type / Coproduct type / Discriminated Union (F#) 
o Pattern matching 
o Generic types 
o Monadic Bind
The tools to pipeline a production process 
o Partial application 
o Summation type / Coproduct type / Discriminated Union (F#) 
o Pattern matching 
o Generic types 
o Monadic Bind 
o Function Composition
Function Composition 
f(x') = w' 
g(x'') = w'' 
h(x''') = w''' 
h( g( f(x) ) ) = w
Function Composition 
let funcOne x = 
funcOne : 'T1 -> 'T2 
let funcTwo x = 
funcTwo : 'T2 -> 'T3 
let compose = funcOne >> funcTwo 
( >> ) : ('T1 -> 'T2) -> ('T2 -> 'T3) -> 'T1 -> 'T3 
compose: 'T1 -> 'T3
Putting it all together 
let processWells = 
steamJob step1Temp step1Bbl 
>> bind (acidJob step2Solution step2Bbl) 
>> bind (steamJob step3Temp step3Bbl) 
>> bind (acidJob step4Solution step4Bbl) 
let run() = 
match processWells wellsToSteam with 
| Success xs -> printfn "success %A" xs 
| Failure exn -> printfn "%s" exn.Message
What could we do better? 
o Is there another step we could take to promote correctness? 
o There are a lot of parameters. 
o Might a programmer easily mix them up in the source code?
Units of Measure 
o Design time types over any numeric type 
o Types check at compile time 
[<Measure>] type degF // degrees Fahrenheit 
[<Measure>] type pct // percent 
[<Measure>] type bbl // barrels 
[<Measure>] type acidId // acid Id 
let step1Temp = 500<degF> 
let step1Bbl = 10000<bbl> 
let step2Solution = 25.0<pct> 
let step2Bbl = 20<bbl> 
let steamJob (temp :int<degF>) (bblOfSteam : int<bbl>) (wells : WellState list) =
So Far… 
o Success / Failure passing 
o Partial Application 
o Types, Summation Type, Generic Types 
o Pattern Matching 
o Modadic Bind 
o Function Composition 
o Units of Measure (design time types)
Async (it’s just another computation expression) 
async { 
} 
The brackets abstracted away a layer of complexity … 
…but at a price.* 
*We lose function composition.
Async (it’s frequently about plumbing) 
async { 
} 
http://commons.wikimedia.org/wiki/File:PSM_V33_D306_Plumbing_arrangement_in_a_19th_century_new_york_house.jpg
let productModel name = async { 
let! result = asyncChoice { 
let! productId = productIdByName name 
let! prodDescription = productAndDescription productI 
let containsFoo = prodDescription.Description.Contains("foo") 
if containsFoo then 
return! async { return Failure ( OutOfBounds("Don't show customers foo")) } 
else 
let descriptionWords = prodDescription.Description.Split(" ".ToCharArray()) 
let! productId2 = productIdByName descriptionWords.[0] 
let! prodDescription2 = productAndDescription productId2 
return prodDescription2.ProductModel 
} 
match result with 
| Success x -> return Success x 
| Failure exn -> return Failure ex 
}
AsyncChoicebuilder * 
member __.Bind … 
member __.Combine (r1, r2) : Async<Choice<'T, 'Error>> = 
async { 
let! r1' = r1 
match r1' with 
| Choice1Of2 () -> 
return! r2 
| Choice2Of2 error -> 
return Choice2Of2 error 
} * ExtCore
asyncChoice { 
let! productId = productIdByName name 
let! prodDescription = productAndDescription productI 
let containsFoo = prodDescription.Description.Contains("foo") 
if containsFoo then 
return! async { return Failure ( OutOfBounds("Don't show customers foo")) } 
else 
let descriptionWords = prodDescription.Description.Split(" ".ToCharArray()) 
let! productId2 = productIdByName descriptionWords.[0] 
let! prodDescription2 = productAndDescription productId2 
return prodDescription2.ProductModel 
} 
binds to value inside the builder 
returns the value inside the 
computation expression 
choice builder’s combine 
composes bound values 
inside “choice” 
“inbetween” regular 
F# syntax and control 
statements
Typing your way into relational data 
o FSharp.Data.SqlClient 
type ProductIdByName = SqlCommandProvider<" 
SELECT ProductID from Production.Product 
WHERE Name = @name 
", connectionString, SingleRow = true> 
write any T-SQL inline, 
“red squigglies” from 
compiler on syntax 
and schema errors 
optional parameter
FSharp.Data.SqlClient 
let productIdByName name = async { 
let! result = 
async { 
return type is a 
record strongly typed 
to result of query 
use cmd = new ProductIdByName() 
return! cmd.AsyncExecute(name = name) 
} 
|> Async.Catch 
parameters indicated by 
intellisense 
in this case return type is 
option 
match result with 
| Choice1Of2 (Some productID) -> return Success productID 
| Choice1Of2 _ -> return Failure ( SelectNotFound() :> Exception ) 
| Choice2Of2 exn -> return Failure exn
Programmability over functions and sprocs 
[<Literal>] 
let connectionString = @"Data Source=.;Initial 
Catalog=AdventureWorks2012;Integrated Security=SSPI" 
type AdventureWorks = SqlProgrammabilityProvider<connectionString> 
type Dbo = AdventureWorks.dbo 
type BillOfMaterials = AdventureWorks.dbo.uspGetBillOfMaterials 
let cmd = new BillOfMaterials() 
cmd.AsyncExecute(1, DateTime.UtcNow) |> Async.RunSynchronously 
return type strongly 
typed to result 
parameters indicated by 
intellisense 
intellisense dot 
completion
SQL Enumeration 
type ProductCategory = SqlEnumProvider<" 
SELECT Name, ProductCategoryID 
FROM Production.ProductCategory", connectionString> 
let AccessoriesId = ProductCategory.Accessories 
intellisense dot 
completion
What we covered 
o Success / Failure passing 
o Partial Application 
o Types, Summation Type, Generic Types 
o Pattern Matching 
o Modadic Bind 
o Function Composition 
o Units of Measure (design time types) 
o Computation Expressions 
o Typing your way into relational data
Questions? 
Bibliography 
o Railway oriented programming 
http://fsharpforfunandprofit.com/posts/recipe-part2/ 
o Computation Expressions 
http://msdn.microsoft.com/en-us/library/dd233182.aspx 
o The F# Computation Expression Zoo 
http://tomasp.net/academic/papers/computation-zoo/computation-zoo.pdf 
o ExtCore, an extended core library for F# 
https://github.com/jack-pappas/ExtCore 
o FSharp.Data.SqlClient 
http://fsprojects.github.io/FSharp.Data.SqlClient/ 
Code: github.com/jackfoxy/Svcc2014Demo Slides: www.slideshare.net/jackfoxy

More Related Content

PDF
Analysis of Microsoft Code Contracts
PDF
Swift 2
PDF
Denis Lebedev, Swift
PDF
Introduction to Swift programming language.
PPT
Falcon初印象
PDF
Programming Language Swift Overview
PDF
Swift Programming Language
PDF
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
Analysis of Microsoft Code Contracts
Swift 2
Denis Lebedev, Swift
Introduction to Swift programming language.
Falcon初印象
Programming Language Swift Overview
Swift Programming Language
[C++ Korea] Effective Modern C++ Study, Item 11 - 13

What's hot (20)

PPTX
Iterative control structures, looping, types of loops, loop working
PDF
Cocoa Design Patterns in Swift
DOC
C operators
PPTX
C++11 - A Change in Style - v2.0
PDF
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
PDF
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1
PPT
FP 201 Unit 2 - Part 3
PPT
FP 201 - Unit 3 Part 2
PDF
Checking the Source Code of FlashDevelop with PVS-Studio
PPTX
C++ Presentation
PPTX
C++ 11 Features
PPTX
Kotlin
PPT
Open SQL & Internal Table
PDF
Oop10 6
PPTX
05. Conditional Statements
PPT
Csphtp1 15
PDF
Functional Programming Patterns (NDC London 2014)
PDF
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
PPT
Paradigmas de Linguagens de Programacao - Aula #4
PPTX
Whats New In C# 4 0 - NetPonto
Iterative control structures, looping, types of loops, loop working
Cocoa Design Patterns in Swift
C operators
C++11 - A Change in Style - v2.0
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1
FP 201 Unit 2 - Part 3
FP 201 - Unit 3 Part 2
Checking the Source Code of FlashDevelop with PVS-Studio
C++ Presentation
C++ 11 Features
Kotlin
Open SQL & Internal Table
Oop10 6
05. Conditional Statements
Csphtp1 15
Functional Programming Patterns (NDC London 2014)
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...
Paradigmas de Linguagens de Programacao - Aula #4
Whats New In C# 4 0 - NetPonto
Ad

Viewers also liked (7)

PDF
Edwardian Proofs as Futuristic Programs
PPTX
Linear structures lightning talk
PPTX
Functional linear data structures in f#
PPTX
Tools for reading papers
PPTX
Introduction to the lambda calculus
PPTX
Intoduction to Homotopy Type Therory
PPTX
Type Theory and Practical Application
Edwardian Proofs as Futuristic Programs
Linear structures lightning talk
Functional linear data structures in f#
Tools for reading papers
Introduction to the lambda calculus
Intoduction to Homotopy Type Therory
Type Theory and Practical Application
Ad

Similar to Functional programming for production quality code (20)

PDF
Functional Programming in F#
PPTX
Столпы функционального программирования для адептов ООП, Николай Мозговой
PPTX
Functional programming with FSharp
PDF
The Functional Programming Toolkit (NDC Oslo 2019)
PDF
F# and Reactive Programming for iOS
PDF
Functional programming with F#
PDF
An introduction to functional programming with Swift
PDF
Functional Design Patterns (DevTernity 2018)
PPTX
Reasonable Code With Fsharp
PDF
[4DEV] Bartosz Sokół - Functional developer in object oriented world - how F#...
PDF
The Power of Composition
PPTX
Intro to Functional Programming
KEY
Exciting JavaScript - Part II
PPTX
Functional-style control flow in F#
PPTX
Intro f# functional_programming
PDF
Functional programming is the most extreme programming
PDF
Introduction to Functional Programming
PDF
Introduction to Functional Programming (w/ JS)
PPTX
Sharper tools with F#
PPTX
Functional DDD
Functional Programming in F#
Столпы функционального программирования для адептов ООП, Николай Мозговой
Functional programming with FSharp
The Functional Programming Toolkit (NDC Oslo 2019)
F# and Reactive Programming for iOS
Functional programming with F#
An introduction to functional programming with Swift
Functional Design Patterns (DevTernity 2018)
Reasonable Code With Fsharp
[4DEV] Bartosz Sokół - Functional developer in object oriented world - how F#...
The Power of Composition
Intro to Functional Programming
Exciting JavaScript - Part II
Functional-style control flow in F#
Intro f# functional_programming
Functional programming is the most extreme programming
Introduction to Functional Programming
Introduction to Functional Programming (w/ JS)
Sharper tools with F#
Functional DDD

Recently uploaded (20)

PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
AI in Product Development-omnex systems
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
System and Network Administration Chapter 2
PPTX
Operating system designcfffgfgggggggvggggggggg
PPTX
Introduction to Artificial Intelligence
PPTX
history of c programming in notes for students .pptx
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Understanding Forklifts - TECH EHS Solution
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Softaken Excel to vCard Converter Software.pdf
Wondershare Filmora 15 Crack With Activation Key [2025
How to Choose the Right IT Partner for Your Business in Malaysia
AI in Product Development-omnex systems
Design an Analysis of Algorithms I-SECS-1021-03
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Design an Analysis of Algorithms II-SECS-1021-03
Reimagine Home Health with the Power of Agentic AI​
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
System and Network Administration Chapter 2
Operating system designcfffgfgggggggvggggggggg
Introduction to Artificial Intelligence
history of c programming in notes for students .pptx
Upgrade and Innovation Strategies for SAP ERP Customers
CHAPTER 2 - PM Management and IT Context
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Understanding Forklifts - TECH EHS Solution

Functional programming for production quality code

  • 1. Functional Programming for Production Quality Code Jack Fox jackfoxy.com  craftyThoughts @foxyjackfox Slides http://www.slideshare.net/jackfoxy Sample Code https://github.com/jackfoxy/Svcc2014Demo
  • 2. Functional Programming for Production Quality Code o Success / Failure passing o Partial Application o Types, Summation Type, Generic Types o Pattern Matching o Modadic Bind o Function Composition o Units of Measure (design time types) o Computation Expressions o Typing your way into relational data
  • 3. Ever seen this code? if condition1 then doThis() if condition2 then doThat() if condition3 then doSomeOtherThing() if condition3 then aTask() if condition4 then anotherTask() if condition5 then yetAnotherTask() if condition5 then finallyDone() else handleError() else handleError() else handleError() else handleError() else handleError() else handleError() else handleError()
  • 4. Functional Programming Remember functions from high school math? f(x) = y one input parameter always maps to the same output
  • 5. Functional Programming Remember functions from high school math? f(x) = y one input parameter always maps to the same output But I need multiple input parameters!
  • 6. A compiler FP trick called “currying” let f x y z = let w = 1 … //do something w //return f(x g(y h(z))) = w wrapping single parameter functions within functions f: x -> (y -> (z -> w)) function signature
  • 7. o You don’t really need to know currying o Instead understand the inverse of currying o Unwrap the parameters of a function o Unwrapping is called “Partial Application”
  • 8. Partial application o If this is a function let steamJob temperature barrelsOfSteam wellsToSteam = … somethingWeReturn steamJob : temperature: int -> barrelsOfSteam: int -> wellsToSteam: WellState list -> int o Then so is this let mySteamJob = steamJob 500 10000 mySteamJob : (WellState list -> int)
  • 9. Next: a short digression into types These are all types o int o string o list o WellState o Exception
  • 10. Summation type o This is a type that takes the form of multiple types o It can only be one of those types at a time o In F# this type is called “discriminated union” type Choice<'T1, 'T2> = | Success of 'T1 | Failure of 'T2 note this in not the actual Choice type in Fsharp.Core
  • 11. Generic types generic types in type constructor type Choice<'T1, 'T2> = | Success of 'T1 | Failure of 'T2
  • 12. Return Summation Type (Discriminated Union) let steamJob2 (temperature :int) (barrelsOfSteam : int) (wellsToSteam : WellState list) = … if … then Success wellsToSteam else Failure (BadSteamJob (sprintf "BadSteamJob temperature %i barrelsOfSteam %i wellsToSteam %A“ temperature barrelsOfSteam wellsToSteam) :> Exception )
  • 13. Return Summation Type (Discriminated Union) let steamJob2 (temperature :int) (barrelsOfSteam : int) (wellsToSteam : WellState list) = … if … then Success wellsToSteam else Failure (BadSteamJob (sprintf "BadSteamJob temperature %i barrelsOfSteam %i wellsToSteam %A“ temperature barrelsOfSteam wellsToSteam) :> Exception ) steamJob : temperature:int -> barrelsOfSteam:int -> wellsToSteam:WellState list -> Choice<WellState list, Exception> generic constructor types replaced with real types
  • 14. let result = steamJob2 500 4000 wellsToSteam match result with | Success steamedWells -> printfn "%A" steamedWells | Failure exn -> printfn "%s" exn.Message steamJob : temperature:int -> barrelsOfSteam:int -> wellsToSteam:WellState list -> Choice<WellState list, Exception> Consuming a Summation Type (Discriminated Union)
  • 15. The tools to pipeline a production process o Partial application o Summation type / Coproduct type / Discriminated Union (F#) o Pattern matching o Generic types
  • 16. The tools to pipeline a production process o Partial application o Summation type / Coproduct type / Discriminated Union (F#) o Pattern matching o Generic types o Monadic Bind
  • 17. Monadic Bind let bind nextFunction lastOutput = match lastOutput with | Success s -> nextFunction s | Failure f -> Failure f bind : nextFunction : ('a -> Choice<'b,'c>) -> lastOutput : Choice<'a,'c> -> Choice<'b,'c> generic constructor types to be replaced with real types
  • 18. Monadic Bind let bind nextFunction lastOutput = match lastOutput with | Success s -> nextFunction s | Failure f -> Failure f the generics line up between nextFunction and lastOutput bind : nextFunction:('a -> Choice<'b,'c>) -> lastOutput:Choice<'a,'c> -> Choice<'b,'c> resulting output lets us chain indefinitely
  • 19. The tools to pipeline a production process o Partial application o Summation type / Coproduct type / Discriminated Union (F#) o Pattern matching o Generic types o Monadic Bind
  • 20. The tools to pipeline a production process o Partial application o Summation type / Coproduct type / Discriminated Union (F#) o Pattern matching o Generic types o Monadic Bind o Function Composition
  • 21. Function Composition f(x') = w' g(x'') = w'' h(x''') = w''' h( g( f(x) ) ) = w
  • 22. Function Composition let funcOne x = funcOne : 'T1 -> 'T2 let funcTwo x = funcTwo : 'T2 -> 'T3 let compose = funcOne >> funcTwo ( >> ) : ('T1 -> 'T2) -> ('T2 -> 'T3) -> 'T1 -> 'T3 compose: 'T1 -> 'T3
  • 23. Putting it all together let processWells = steamJob step1Temp step1Bbl >> bind (acidJob step2Solution step2Bbl) >> bind (steamJob step3Temp step3Bbl) >> bind (acidJob step4Solution step4Bbl) let run() = match processWells wellsToSteam with | Success xs -> printfn "success %A" xs | Failure exn -> printfn "%s" exn.Message
  • 24. What could we do better? o Is there another step we could take to promote correctness? o There are a lot of parameters. o Might a programmer easily mix them up in the source code?
  • 25. Units of Measure o Design time types over any numeric type o Types check at compile time [<Measure>] type degF // degrees Fahrenheit [<Measure>] type pct // percent [<Measure>] type bbl // barrels [<Measure>] type acidId // acid Id let step1Temp = 500<degF> let step1Bbl = 10000<bbl> let step2Solution = 25.0<pct> let step2Bbl = 20<bbl> let steamJob (temp :int<degF>) (bblOfSteam : int<bbl>) (wells : WellState list) =
  • 26. So Far… o Success / Failure passing o Partial Application o Types, Summation Type, Generic Types o Pattern Matching o Modadic Bind o Function Composition o Units of Measure (design time types)
  • 27. Async (it’s just another computation expression) async { } The brackets abstracted away a layer of complexity … …but at a price.* *We lose function composition.
  • 28. Async (it’s frequently about plumbing) async { } http://commons.wikimedia.org/wiki/File:PSM_V33_D306_Plumbing_arrangement_in_a_19th_century_new_york_house.jpg
  • 29. let productModel name = async { let! result = asyncChoice { let! productId = productIdByName name let! prodDescription = productAndDescription productI let containsFoo = prodDescription.Description.Contains("foo") if containsFoo then return! async { return Failure ( OutOfBounds("Don't show customers foo")) } else let descriptionWords = prodDescription.Description.Split(" ".ToCharArray()) let! productId2 = productIdByName descriptionWords.[0] let! prodDescription2 = productAndDescription productId2 return prodDescription2.ProductModel } match result with | Success x -> return Success x | Failure exn -> return Failure ex }
  • 30. AsyncChoicebuilder * member __.Bind … member __.Combine (r1, r2) : Async<Choice<'T, 'Error>> = async { let! r1' = r1 match r1' with | Choice1Of2 () -> return! r2 | Choice2Of2 error -> return Choice2Of2 error } * ExtCore
  • 31. asyncChoice { let! productId = productIdByName name let! prodDescription = productAndDescription productI let containsFoo = prodDescription.Description.Contains("foo") if containsFoo then return! async { return Failure ( OutOfBounds("Don't show customers foo")) } else let descriptionWords = prodDescription.Description.Split(" ".ToCharArray()) let! productId2 = productIdByName descriptionWords.[0] let! prodDescription2 = productAndDescription productId2 return prodDescription2.ProductModel } binds to value inside the builder returns the value inside the computation expression choice builder’s combine composes bound values inside “choice” “inbetween” regular F# syntax and control statements
  • 32. Typing your way into relational data o FSharp.Data.SqlClient type ProductIdByName = SqlCommandProvider<" SELECT ProductID from Production.Product WHERE Name = @name ", connectionString, SingleRow = true> write any T-SQL inline, “red squigglies” from compiler on syntax and schema errors optional parameter
  • 33. FSharp.Data.SqlClient let productIdByName name = async { let! result = async { return type is a record strongly typed to result of query use cmd = new ProductIdByName() return! cmd.AsyncExecute(name = name) } |> Async.Catch parameters indicated by intellisense in this case return type is option match result with | Choice1Of2 (Some productID) -> return Success productID | Choice1Of2 _ -> return Failure ( SelectNotFound() :> Exception ) | Choice2Of2 exn -> return Failure exn
  • 34. Programmability over functions and sprocs [<Literal>] let connectionString = @"Data Source=.;Initial Catalog=AdventureWorks2012;Integrated Security=SSPI" type AdventureWorks = SqlProgrammabilityProvider<connectionString> type Dbo = AdventureWorks.dbo type BillOfMaterials = AdventureWorks.dbo.uspGetBillOfMaterials let cmd = new BillOfMaterials() cmd.AsyncExecute(1, DateTime.UtcNow) |> Async.RunSynchronously return type strongly typed to result parameters indicated by intellisense intellisense dot completion
  • 35. SQL Enumeration type ProductCategory = SqlEnumProvider<" SELECT Name, ProductCategoryID FROM Production.ProductCategory", connectionString> let AccessoriesId = ProductCategory.Accessories intellisense dot completion
  • 36. What we covered o Success / Failure passing o Partial Application o Types, Summation Type, Generic Types o Pattern Matching o Modadic Bind o Function Composition o Units of Measure (design time types) o Computation Expressions o Typing your way into relational data
  • 37. Questions? Bibliography o Railway oriented programming http://fsharpforfunandprofit.com/posts/recipe-part2/ o Computation Expressions http://msdn.microsoft.com/en-us/library/dd233182.aspx o The F# Computation Expression Zoo http://tomasp.net/academic/papers/computation-zoo/computation-zoo.pdf o ExtCore, an extended core library for F# https://github.com/jack-pappas/ExtCore o FSharp.Data.SqlClient http://fsprojects.github.io/FSharp.Data.SqlClient/ Code: github.com/jackfoxy/Svcc2014Demo Slides: www.slideshare.net/jackfoxy