SlideShare a Scribd company logo
embrace the paradigm
REASONABLE CODE WITH F#
ABOUT ME
SECTION: OVERVIEW
Help the human
SYNTAX
int euler1(int max) {
var total = 0;
for(var n=1; n<max; n++) {
if(n % 3 == 0 || n % 5 == 0){
total += n;
}
}
return total;
}
euler1(1000);
C#
let euler1 max =
[1..max-1]
|> List.filter (fun n -> n % 3 = 0 || n % 5 = 0)
|> List.sum
euler1 1000
F#
SYNTAX – VS LINQ
int euler1(int max) {
return Enumerable.Range(1, max - 1)
.Where(n => n % 3 == 0 || n % 5 == 0)
.Sum();
}
euler1(1000);
C#
let euler1 max =
[1..max-1]
|> List.filter (fun n -> n % 3 = 0 || n % 5 = 0)
|> List.sum
euler1 1000
F#
TYPE INFERENCE
int x = 3;
long y = 4;
var z = x + y; // = 7
C# let x = 3
let y:int64 = 4L
x + y
F#
The type 'int64' does not
match the type 'int'
AUTOMATIC GENERALIZATION
val firstInGroup :
g:('a -> 'b) -> list:seq<'a> -> seq<'b * 'a> when 'b : equality
public IEnumerable<Tuple<U,T>> firstInGroup<T,U>
(Func<T,U> g, IEnumerable<T> list) {
return list.GroupBy(g)
.Select(grp => new Tuple<U, T>(grp.Key, grp.First()));
}
C#
let firstInGroup g list =
list
|> Seq.groupBy g
|> Seq.map (fun (key,items) -> key, Seq.head items)
F#
GENERALIZE THIS!
int add<T>(T x, T y) where T: op_addition {
return x + y;
}
C#
let add x y = x + y
add 3 4
add 4.2 5.1
F# let inline add x y = x + y
add 3 4
add 4.2 5.1
add "hello" "World"
F#
IMMUTABILITY
Eliminate unintended side effects
Sets you up for multi-core programming
Debugging is easier
Testability is higher
Intended side effects are necessary
Performance
IMMUTABILITY - EXAMPLE
Example from “Inside F#” blog
let actions = List.init 5 (fun i -> fun() -> i*2)
for act in actions do
printf "%d " (act())
F#
List<Func<int>> actions = new List<Func<int>>();
for (int i = 0; i < 5; ++i) {
actions.Add( () => i * 2 );
}
foreach (var act in actions) {
Console.WriteLine( act() );
}
C#
The mutable variable 'i' is used in an invalid way.
Mutable variables cannot be captured by closures.
Consider eliminating this use of mutation or using a
heap-allocated mutable reference cell via 'ref' and '!'.
OVERVIEW
1.Human readable
2.Reusability
3.Sensible defaults
FUNCTIONS AND FUNCTIONAL TYPES
Which problem would you rather focus on?
a) Where the code should live
b) What the code should do
COMPOSITION VS INHERITANCE
Is-a relationship that extends the base class
Very high coupling
Subclasses may not need all functionality from base class
Subclass has to be aware of the base class’s implementation
Ninject StructureMap
Castle WindsorUnity
Interface-dependent
FUNCTION COMPOSITION
Pipeline Operator: |>
Return value of first function becomes the last parameter of second function
Forward Composition Operator: >>
Create new functions that are sequences of existing functions
webUrl
|> downloadPage |> extractMetaInfo |> categorizeResource
F#
let categorizeUrl =
downloadPage >> extractMetaInfo >> categorizeResource
let categorizeEmail =
parseEmail >> extractDetail >> categorizeResource
categorizeUrl webUrl
categorizeEmail email
F#
FUNCTION COMPOSITION
Partial Application
Create new functions by supplying some of the arguments to an existing function
let MSBuild properties (outputPath:string) (targets:string) =
//Do some msbuild stuff
let MSBuildDebug = MSBuild ["Configuration","Debug"]
let MSBuildRelease = MSBuild ["Configuration","Release"]
F#
* From FAKE
PATTERN MATCHING
let data = ("Cleveland", 390000)
let city, population = data
F#
let x = 9
match x with
| num when num < 10 -> printfn "Less than ten"
| _ -> printfn "Greater than or equal to ten"
F#
DISCRIMINATED UNIONS
type Shape =
| Square of int
| Rectangle of float*float
| Circle of float
F#
let getArea shape =
match shape with
| Square side -> float(side * side)
| Rectangle(w,h) -> w * h
| Circle r -> System.Math.PI * r * r
F#
let sq = Square 7
let rect = Rectangle 2.2 3.3
let cir = Circle 3.4
F#
OPTION TYPE
type Option<‘T> =
| None
| Some of ‘T
F#
OBJECT MODELING
* From F# Deep Dives
type MarkdownDocument = list<MarkdownBlock>
and MarkdownBlock =
| Heading of int * MarkdownSpans
| Paragraph of MarkdownSpans
| CodeBlock of list<string>
and MarkdownSpans = list<MarkdownSpan>
and MarkdownSpan =
| Literal of string
| InlineCode of string
| Strong of MarkdownSpans
| Emphasis of MarkdownSpans
| Hyperlink of MarkdownSpans * string
F#
FUNCTIONS AND FUNCTIONAL TYPES
1.Think small, build big
2.Model
3.Flow
COMPILER CHECKED CORRECTNESS
Step 1: Create types
Step 2: Lean on the compiler
UNITS OF MEASURE
unitsOfMeasure.fsx(11,19): error FS0001: Type mismatch. Expecting a
int<mi> []
but given a
int<km> []
The unit of measure 'mi' does not match the unit of measure 'km'
[<Measure>]
type mi
[<Measure>]
type km
// define some values
let mike = [| 6<mi>; 9<mi>; 5<mi>; 18<mi> |]
let chris = [| 3<km>; 5<km>; 2<km>; 8<km> |]
let totalDistance = (Array.append mike chris) |> Array.sum
F#
UNITS OF MEASURE
enum DistanceUnit {
Miles,
Kilometers
}
class Run {
private float distance;
private DistanceUnit unit;
public Run(float distance, DistanceUnit unit){
this.distance = distance;
this.unit = unit;
}
}
C#
EXHAUSTIVE PATTERN MATCHING
//Model
module Person =
type T = Person of string
let create name =
if String.IsNullOrWhiteSpace(name) then None
else Some(Person name)
let value (Person p) = p
//DAL
let save person =
//put the person in the database…
Some 42
//UI
let readInput name =
match Person.create name with
| None -> printfn "Please supply a name"
| Some p ->
match save p with
| None -> printfn "An error occurred"
| Some id -> printfn "The id for %s is %d" (Person.value p) id
F#
EXHAUSTIVE PATTERN MATCHING
//DAL
type DatabaseResult<'a> =
| Success of 'a
| UniqueViolation
| GeneralException of Exception
//UI
let readInput name =
match Person.create name with
| None -> printfn "Please supply a name"
| Some p ->
match save p with
| Success(id) ->
printfn "The id for %s is %d" (Person.value p) id
| UniqueViolation ->
printfn "The name %s already exists" (Person.value p)
| GeneralException(ex) ->
printfn "%s" ex.Message
F#
DATABASE ACCESS, TOO?
Amount of code added to project
COMPILER CHECKED CORRECTNESS
1.Focus on the problem
2.Don’t forget stuff
SUMMARY
To Reason: To make sense of
Syntax & Idioms
Functional composition
Compiler-checked correctness
NOW WHAT?

More Related Content

What's hot

Rx workshop
Rx workshopRx workshop
Rx workshop
Ryan Riley
 
Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programming
Scott Wlaschin
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#bleis tift
 
F# Presentation
F# PresentationF# Presentation
F# Presentationmrkurt
 
Time for Functions
Time for FunctionsTime for Functions
Time for Functions
simontcousins
 
Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)
IoT Code Lab
 
Advance python programming
Advance python programming Advance python programming
Advance python programming
Jagdish Chavan
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definition
Eelco Visser
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
Mohd Sajjad
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
climatewarrior
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
AmIt Prasad
 
Sharper tools with F#
Sharper tools with F#Sharper tools with F#
Sharper tools with F#
Kevin Avignon
 
Chapter 2 Decision Making (Python Programming Lecture)
Chapter 2 Decision Making (Python Programming Lecture)Chapter 2 Decision Making (Python Programming Lecture)
Chapter 2 Decision Making (Python Programming Lecture)
IoT Code Lab
 
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Philip Schwarz
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
Sikder Tahsin Al-Amin
 
Railway Oriented Programming
Railway Oriented ProgrammingRailway Oriented Programming
Railway Oriented Programming
Scott Wlaschin
 
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Philip Schwarz
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and Loops
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - FunctionsPython Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - Functions
P3 InfoTech Solutions Pvt. Ltd.
 
Python unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusPython unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabus
DhivyaSubramaniyam
 

What's hot (20)

Rx workshop
Rx workshopRx workshop
Rx workshop
 
Pipeline oriented programming
Pipeline oriented programmingPipeline oriented programming
Pipeline oriented programming
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#
 
F# Presentation
F# PresentationF# Presentation
F# Presentation
 
Time for Functions
Time for FunctionsTime for Functions
Time for Functions
 
Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)
 
Advance python programming
Advance python programming Advance python programming
Advance python programming
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definition
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
 
Sharper tools with F#
Sharper tools with F#Sharper tools with F#
Sharper tools with F#
 
Chapter 2 Decision Making (Python Programming Lecture)
Chapter 2 Decision Making (Python Programming Lecture)Chapter 2 Decision Making (Python Programming Lecture)
Chapter 2 Decision Making (Python Programming Lecture)
 
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Railway Oriented Programming
Railway Oriented ProgrammingRailway Oriented Programming
Railway Oriented Programming
 
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
Game of Life - Polyglot FP - Haskell, Scala, Unison - Part 2 - with minor cor...
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and Loops
 
Python Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - FunctionsPython Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - Functions
 
Python unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusPython unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabus
 

Viewers also liked

Don't Do Agile, Be Agile
Don't Do Agile, Be AgileDon't Do Agile, Be Agile
Don't Do Agile, Be Agile
Michael Falanga
 
نشاط هرمي
نشاط هرمينشاط هرمي
نشاط هرميguest9b857e
 
第62回 イノベーションのジレンマ②「市場調査やアンケート調査 」vs「行動観察」
第62回 イノベーションのジレンマ②「市場調査やアンケート調査 」vs「行動観察」第62回 イノベーションのジレンマ②「市場調査やアンケート調査 」vs「行動観察」
第62回 イノベーションのジレンマ②「市場調査やアンケート調査 」vs「行動観察」
Mitsuhiro Shimada
 
Software as a Service
Software as a ServiceSoftware as a Service
Software as a Service
Michael Falanga
 
第72回 レッドブル翼をさずける② 完結編 単なるスポーツマーケティングではない
第72回 レッドブル翼をさずける② 完結編 単なるスポーツマーケティングではない第72回 レッドブル翼をさずける② 完結編 単なるスポーツマーケティングではない
第72回 レッドブル翼をさずける② 完結編 単なるスポーツマーケティングではない
Mitsuhiro Shimada
 
Yellowstone national park
Yellowstone national parkYellowstone national park
Yellowstone national parksamantha25
 
第75回 スポーツマーケティング③スポーツマーケティングの構造&amp;テレビとスポーツ
第75回 スポーツマーケティング③スポーツマーケティングの構造&amp;テレビとスポーツ第75回 スポーツマーケティング③スポーツマーケティングの構造&amp;テレビとスポーツ
第75回 スポーツマーケティング③スポーツマーケティングの構造&amp;テレビとスポーツ
Mitsuhiro Shimada
 

Viewers also liked (7)

Don't Do Agile, Be Agile
Don't Do Agile, Be AgileDon't Do Agile, Be Agile
Don't Do Agile, Be Agile
 
نشاط هرمي
نشاط هرمينشاط هرمي
نشاط هرمي
 
第62回 イノベーションのジレンマ②「市場調査やアンケート調査 」vs「行動観察」
第62回 イノベーションのジレンマ②「市場調査やアンケート調査 」vs「行動観察」第62回 イノベーションのジレンマ②「市場調査やアンケート調査 」vs「行動観察」
第62回 イノベーションのジレンマ②「市場調査やアンケート調査 」vs「行動観察」
 
Software as a Service
Software as a ServiceSoftware as a Service
Software as a Service
 
第72回 レッドブル翼をさずける② 完結編 単なるスポーツマーケティングではない
第72回 レッドブル翼をさずける② 完結編 単なるスポーツマーケティングではない第72回 レッドブル翼をさずける② 完結編 単なるスポーツマーケティングではない
第72回 レッドブル翼をさずける② 完結編 単なるスポーツマーケティングではない
 
Yellowstone national park
Yellowstone national parkYellowstone national park
Yellowstone national park
 
第75回 スポーツマーケティング③スポーツマーケティングの構造&amp;テレビとスポーツ
第75回 スポーツマーケティング③スポーツマーケティングの構造&amp;テレビとスポーツ第75回 スポーツマーケティング③スポーツマーケティングの構造&amp;テレビとスポーツ
第75回 スポーツマーケティング③スポーツマーケティングの構造&amp;テレビとスポーツ
 

Similar to Reasonable Code With Fsharp

F# intro
F# introF# intro
F# intro
Alexey Raga
 
Begin with Python
Begin with PythonBegin with Python
Begin with Python
Narong Intiruk
 
F# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, HerefordF# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, Hereford
Kit Eason
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
Luis Atencio
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
Tushar B Kute
 
MP in Clojure
MP in ClojureMP in Clojure
MP in Clojure
Kent Ohashi
 
Arrow 101 - Kotlin funcional com Arrow
Arrow 101 - Kotlin funcional com ArrowArrow 101 - Kotlin funcional com Arrow
Arrow 101 - Kotlin funcional com Arrow
Leandro Ferreira
 
Functional programming with FSharp
Functional programming with FSharpFunctional programming with FSharp
Functional programming with FSharp
Daniele Pozzobon
 
FParsec Hands On - F#unctional Londoners 2014
FParsec Hands On -  F#unctional Londoners 2014FParsec Hands On -  F#unctional Londoners 2014
FParsec Hands On - F#unctional Londoners 2014
Phillip Trelford
 
Build a compiler in 2hrs - NCrafts Paris 2015
Build a compiler in 2hrs -  NCrafts Paris 2015Build a compiler in 2hrs -  NCrafts Paris 2015
Build a compiler in 2hrs - NCrafts Paris 2015
Phillip Trelford
 
L25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptxL25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptx
happycocoman
 
Deep Dive Into Swift
Deep Dive Into SwiftDeep Dive Into Swift
Deep Dive Into Swift
Sarath C
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5alish sha
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in ruby
Koen Handekyn
 
Introduction to ES2015
Introduction to ES2015Introduction to ES2015
Introduction to ES2015
kiranabburi
 
Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)
Sumant Tambe
 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
Sumant Tambe
 
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCEFUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
Venugopalavarma Raja
 

Similar to Reasonable Code With Fsharp (20)

F# intro
F# introF# intro
F# intro
 
Begin with Python
Begin with PythonBegin with Python
Begin with Python
 
F# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, HerefordF# Presentation for SmartDevs, Hereford
F# Presentation for SmartDevs, Hereford
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
 
MP in Clojure
MP in ClojureMP in Clojure
MP in Clojure
 
Arrow 101 - Kotlin funcional com Arrow
Arrow 101 - Kotlin funcional com ArrowArrow 101 - Kotlin funcional com Arrow
Arrow 101 - Kotlin funcional com Arrow
 
Functional programming with FSharp
Functional programming with FSharpFunctional programming with FSharp
Functional programming with FSharp
 
FParsec Hands On - F#unctional Londoners 2014
FParsec Hands On -  F#unctional Londoners 2014FParsec Hands On -  F#unctional Londoners 2014
FParsec Hands On - F#unctional Londoners 2014
 
Build a compiler in 2hrs - NCrafts Paris 2015
Build a compiler in 2hrs -  NCrafts Paris 2015Build a compiler in 2hrs -  NCrafts Paris 2015
Build a compiler in 2hrs - NCrafts Paris 2015
 
Vcs16
Vcs16Vcs16
Vcs16
 
L25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptxL25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptx
 
Deep Dive Into Swift
Deep Dive Into SwiftDeep Dive Into Swift
Deep Dive Into Swift
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in ruby
 
Introduction to ES2015
Introduction to ES2015Introduction to ES2015
Introduction to ES2015
 
Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)
 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
 
functions
functionsfunctions
functions
 
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCEFUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
 

Recently uploaded

Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 

Recently uploaded (20)

Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 

Reasonable Code With Fsharp

  • 4. SYNTAX int euler1(int max) { var total = 0; for(var n=1; n<max; n++) { if(n % 3 == 0 || n % 5 == 0){ total += n; } } return total; } euler1(1000); C# let euler1 max = [1..max-1] |> List.filter (fun n -> n % 3 = 0 || n % 5 = 0) |> List.sum euler1 1000 F#
  • 5. SYNTAX – VS LINQ int euler1(int max) { return Enumerable.Range(1, max - 1) .Where(n => n % 3 == 0 || n % 5 == 0) .Sum(); } euler1(1000); C# let euler1 max = [1..max-1] |> List.filter (fun n -> n % 3 = 0 || n % 5 = 0) |> List.sum euler1 1000 F#
  • 6. TYPE INFERENCE int x = 3; long y = 4; var z = x + y; // = 7 C# let x = 3 let y:int64 = 4L x + y F# The type 'int64' does not match the type 'int'
  • 7. AUTOMATIC GENERALIZATION val firstInGroup : g:('a -> 'b) -> list:seq<'a> -> seq<'b * 'a> when 'b : equality public IEnumerable<Tuple<U,T>> firstInGroup<T,U> (Func<T,U> g, IEnumerable<T> list) { return list.GroupBy(g) .Select(grp => new Tuple<U, T>(grp.Key, grp.First())); } C# let firstInGroup g list = list |> Seq.groupBy g |> Seq.map (fun (key,items) -> key, Seq.head items) F#
  • 8. GENERALIZE THIS! int add<T>(T x, T y) where T: op_addition { return x + y; } C# let add x y = x + y add 3 4 add 4.2 5.1 F# let inline add x y = x + y add 3 4 add 4.2 5.1 add "hello" "World" F#
  • 9. IMMUTABILITY Eliminate unintended side effects Sets you up for multi-core programming Debugging is easier Testability is higher Intended side effects are necessary Performance
  • 10. IMMUTABILITY - EXAMPLE Example from “Inside F#” blog let actions = List.init 5 (fun i -> fun() -> i*2) for act in actions do printf "%d " (act()) F# List<Func<int>> actions = new List<Func<int>>(); for (int i = 0; i < 5; ++i) { actions.Add( () => i * 2 ); } foreach (var act in actions) { Console.WriteLine( act() ); } C# The mutable variable 'i' is used in an invalid way. Mutable variables cannot be captured by closures. Consider eliminating this use of mutation or using a heap-allocated mutable reference cell via 'ref' and '!'.
  • 12. FUNCTIONS AND FUNCTIONAL TYPES Which problem would you rather focus on? a) Where the code should live b) What the code should do
  • 13. COMPOSITION VS INHERITANCE Is-a relationship that extends the base class Very high coupling Subclasses may not need all functionality from base class Subclass has to be aware of the base class’s implementation Ninject StructureMap Castle WindsorUnity Interface-dependent
  • 14. FUNCTION COMPOSITION Pipeline Operator: |> Return value of first function becomes the last parameter of second function Forward Composition Operator: >> Create new functions that are sequences of existing functions webUrl |> downloadPage |> extractMetaInfo |> categorizeResource F# let categorizeUrl = downloadPage >> extractMetaInfo >> categorizeResource let categorizeEmail = parseEmail >> extractDetail >> categorizeResource categorizeUrl webUrl categorizeEmail email F#
  • 15. FUNCTION COMPOSITION Partial Application Create new functions by supplying some of the arguments to an existing function let MSBuild properties (outputPath:string) (targets:string) = //Do some msbuild stuff let MSBuildDebug = MSBuild ["Configuration","Debug"] let MSBuildRelease = MSBuild ["Configuration","Release"] F# * From FAKE
  • 16. PATTERN MATCHING let data = ("Cleveland", 390000) let city, population = data F# let x = 9 match x with | num when num < 10 -> printfn "Less than ten" | _ -> printfn "Greater than or equal to ten" F#
  • 17. DISCRIMINATED UNIONS type Shape = | Square of int | Rectangle of float*float | Circle of float F# let getArea shape = match shape with | Square side -> float(side * side) | Rectangle(w,h) -> w * h | Circle r -> System.Math.PI * r * r F# let sq = Square 7 let rect = Rectangle 2.2 3.3 let cir = Circle 3.4 F#
  • 18. OPTION TYPE type Option<‘T> = | None | Some of ‘T F#
  • 19. OBJECT MODELING * From F# Deep Dives type MarkdownDocument = list<MarkdownBlock> and MarkdownBlock = | Heading of int * MarkdownSpans | Paragraph of MarkdownSpans | CodeBlock of list<string> and MarkdownSpans = list<MarkdownSpan> and MarkdownSpan = | Literal of string | InlineCode of string | Strong of MarkdownSpans | Emphasis of MarkdownSpans | Hyperlink of MarkdownSpans * string F#
  • 20. FUNCTIONS AND FUNCTIONAL TYPES 1.Think small, build big 2.Model 3.Flow
  • 21. COMPILER CHECKED CORRECTNESS Step 1: Create types Step 2: Lean on the compiler
  • 22. UNITS OF MEASURE unitsOfMeasure.fsx(11,19): error FS0001: Type mismatch. Expecting a int<mi> [] but given a int<km> [] The unit of measure 'mi' does not match the unit of measure 'km' [<Measure>] type mi [<Measure>] type km // define some values let mike = [| 6<mi>; 9<mi>; 5<mi>; 18<mi> |] let chris = [| 3<km>; 5<km>; 2<km>; 8<km> |] let totalDistance = (Array.append mike chris) |> Array.sum F#
  • 23. UNITS OF MEASURE enum DistanceUnit { Miles, Kilometers } class Run { private float distance; private DistanceUnit unit; public Run(float distance, DistanceUnit unit){ this.distance = distance; this.unit = unit; } } C#
  • 24. EXHAUSTIVE PATTERN MATCHING //Model module Person = type T = Person of string let create name = if String.IsNullOrWhiteSpace(name) then None else Some(Person name) let value (Person p) = p //DAL let save person = //put the person in the database… Some 42 //UI let readInput name = match Person.create name with | None -> printfn "Please supply a name" | Some p -> match save p with | None -> printfn "An error occurred" | Some id -> printfn "The id for %s is %d" (Person.value p) id F#
  • 25. EXHAUSTIVE PATTERN MATCHING //DAL type DatabaseResult<'a> = | Success of 'a | UniqueViolation | GeneralException of Exception //UI let readInput name = match Person.create name with | None -> printfn "Please supply a name" | Some p -> match save p with | Success(id) -> printfn "The id for %s is %d" (Person.value p) id | UniqueViolation -> printfn "The name %s already exists" (Person.value p) | GeneralException(ex) -> printfn "%s" ex.Message F#
  • 26. DATABASE ACCESS, TOO? Amount of code added to project
  • 27. COMPILER CHECKED CORRECTNESS 1.Focus on the problem 2.Don’t forget stuff
  • 28. SUMMARY To Reason: To make sense of Syntax & Idioms Functional composition Compiler-checked correctness

Editor's Notes

  1. F# language make code easier to understandCan you use F# for a wide range of problems
  2. Small teams, close to businessCut teeth on XPPFP
  3. Who has written any F#?Who gets paid to write F#?A lot like most of you: not an expert.Wanted to stretch my brain like what I see so far I want to share
  4. {} () ; returnNot completely noise…Compiler needs curly bracesIndentingLINQ: adds a lot to readability, but uses:higher order functionsChaining – tied to an interface
  5. Let’s talk about types
  6. - Code reuse! You don’t see the constraints, you see the concepts – the behavior.
  7. &quot;inline“- gives per-type versions of the function, big performance gain over generics- Needed for code that uses overloaded operators – they statically resolve to the default (usually int)
  8. Makes your code more predictableThe default is immutability“minimization” not “elimination”Immutable objects are thread safe
  9. 10 10 10 10 100 2 4 6 8
  10. SyntaxGeneralizationImmutability
  11. F# is a hybridThesethings are not available in the C# language
  12. Composition: pass dependencies at runtime into an instance. Operations are interface-dependentLook back at LINQ exampleTalk about “function composition” in F#...
  13. PipelineDefine a sequence of operationsAny function can be a part of the pipeline – not limited to a particular interfaceForward composition
  14. Great in libraries to create functions that take defaultsOr for eliminating boolean parameters, making existing libraries easier to work with
  15. Decompose or extract specific infoCompare data with a structurelet binding AND program control
  16. “Object reference not set to an instance of an object.”Very important – eliminatesNullReferenceExceptionsWith pattern matching, forces client code to check for None
  17. Simple to understandInstead of strings named “Literal”, “Literal” is a type
  18. Model: use functional types to concisely represent complex object models (especially hierarchies)Flow: most appsTake data inDo some workShow results of workBecause immutable, your thinking changes from “mutate the object” to represent the results to “transform” some data
  19. Compilers are nice because they tell us when we do something bad.What if the compiler was more proactive (like in the immutability example)?
  20. Annotate values in your code with units
  21. Just a structure. Not even values…. “new” up a bunch, etc.Think of the work to get the compiler to tell you when you attempt to add miles and kilometers!point: I’m sure it’s possible. But it won’t be nearly as concise or readable.
  22. You have to deal with return values.
  23. Patterns are exhaustiveNot only detects missingImpossibleRedundant
  24. Have to know what the state of the model is compared to the state of the database
  25. UOM: always compare apples to applesPM: compiler checks for edge cases; forces you to dealTP: don’t worry about state of two disconnected things
  26. Same input, same output; test in isolationCreate functions that solve small problems in your domain (Lego™ blocks), then combine themCreate types that enforce correctness, and force clients to follow the rules
  27. Don’t ignore other functional languages – like OO, there’s a lot to learn from other languagescaml or lisp basedThink polyglot – use functional where you think you can.