SlideShare a Scribd company logo
F# for C# programmers
@ScottWlaschin
fsharpforfunandprofit.com
A language that doesn't affect the way you
think about programming, is not worth
knowing – Alan Perlis
“F# is slightly better than C#,
but not so much that it's
really worth the effort to
move towards it.”
“Learning F# was one of the biggest
boosts in my career as a C# developer.
I don't use it professionally (I wish I
could) but this knowledge made me a
better programmer.”
About F#
• Developed by Microsoft Research
– Shipped withVisual Studio in 2010
• Open source
– On github
• Cross platform
– Works withVS Code (and other editors)
• Very active and friendly community.
– Start with fsharp.org
– F# Slack channel
– #fsharp onTwitter
A tour of F#
• Differences between C# and F#
– Concise syntax
– Type inference
– Different defaults
– Different philosophy
• Special to F#
– Functional-first
– Algebraic type system
– Interactivity
From least to most
important!
SYNTAX
public class Person
{
public Person(string name, DateTime birthday)
{
_name = name;
_birthday = birthday;
}
private readonly string _name;
private readonly DateTime _birthday;
public string Name
{
get { return _name; }
}
public DateTime Birthday
{
get { return _birthday; }
}
}
Syntax difference:
Indentation instead
of curly braces
public class Person
{
public Person(string name, DateTime birthday)
{
_name = name;
_birthday = birthday;
}
private readonly string _name;
private readonly DateTime _birthday;
public string Name
{
get { return _name; }
}
public DateTime Birthday
{
get { return _birthday; }
}
}
Do we really need the
braces?
The indentation already gives
us all the clues we need.
public class Person
{
public Person(string name, DateTime birthday)
{
_name = name;
_birthday = birthday;
}
private readonly string _name;
private readonly DateTime _birthday;
public string Name
{
get { return _name; }
}
public DateTime Birthday
{
get { return _birthday; }
}
}
Example where braces
indicate blocks
public class Person =
public Person(string name, DateTime birthday) =
_name = name;
_birthday = birthday;
private readonly string _name;
private readonly DateTime _birthday;
public string Name =
get { return _name; }
public DateTime Birthday =
get { return _birthday; }
Example where indentation
indicates blocks
Is it really that much
harder to read?
public class Person =
public Person(string name, DateTime birthday) =
_name = name;
_birthday = birthday;
private readonly string _name;
private readonly DateTime _birthday;
public string Name =
get { return _name; }
public DateTime Birthday =
get { return _birthday; }
Use '=' to start blocks
public class Person =
public Person(string name, DateTime birthday) =
_name = name;
_birthday = birthday;
private readonly string _name;
private readonly DateTime _birthday;
public string Name =
get { return _name; }
public DateTime Birthday =
get { return _birthday; }
Shift up to use less
vertical space
People who
complain about
using a language
with syntactic
whitespace
People who
have spent time
using a language
with syntactic
whitespace
"Oddly enough, Python's use of whitespace stopped feeling unnatural
after about twenty minutes. I just indented code, pretty much as I would
have done in a C program anyway, and it worked."
- Eric Raymond
HelpfulVenn Diagram
Overlap
Syntax difference:
Automatically create
backing fields from
constructor parameters
public class Person =
public Person(string name, DateTime birthday) =
_name = name;
_birthday = birthday;
private readonly string _name;
private readonly DateTime _birthday;
public string Name =
get { return _name; }
public DateTime Birthday =
get { return _birthday; }
A lot of duplication...
public class Person =
public Person(string name, DateTime birthday) =
...
public string Name =
get { return name; }
public DateTime Birthday =
get { return birthday; }
Use the constructor params directly
Syntax difference:
Merge the primary constructor
with the class definition
public class Person =
public Person(string name, DateTime birthday) =
...
public string Name =
get { return name; }
public DateTime Birthday =
get { return birthday; }
How often do you have more
than one constructor?
public class Person(string name, DateTime birthday) =
public string Name =
get { return name; }
public DateTime Birthday =
get { return birthday; }
Syntax difference:
Less syntax noise
public class Person(string name, DateTime birthday) =
public string Name =
get { return name; }
public DateTime Birthday =
get { return birthday; }
So why use ‘get’?
The class is immutable.
Every property is "get" only.
public class Person(string name, DateTime birthday) =
public string Name =
return name;
public DateTime Birthday =
return birthday; 'get' is gone!
public class Person(string name, DateTime birthday) =
public string Name =
return name;
public DateTime Birthday =
return birthday;
Who even likes typing semicolons anyway?
public class Person(string name, DateTime birthday) =
public string Name =
return name
public DateTime Birthday =
return birthday
Semicolons gone!
Syntax difference:
No “return” needed
public class Person(string name, DateTime birthday) =
public string Name =
return name
public DateTime Birthday =
return birthday
public class Person(string name, DateTime birthday) =
public string Name =
name
public DateTime Birthday =
birthday
F# is an expression-
oriented language
Difference:
Members are public by default
public class Person(string name, DateTime birthday) =
public string Name =
name
public DateTime Birthday =
birthday
class Person(string name, DateTime birthday) =
string Name =
name
DateTime Birthday =
birthday
Difference:
Type inference!
class Person(string name, DateTime birthday) =
string Name =
name
DateTime Birthday =
birthday
Why do we have to
repeat the type?
Can't the compiler
figure it out for us?
class Person(string name, DateTime birthday) =
Name =
name
Birthday =
birthday
class Person(string name, DateTime birthday) =
member this.Name =
name
member this.Birthday =
birthday
class Person(string name, DateTime birthday) =
member this.Name =
name
member this.Birthday =
birthday
member this.Age() =
var daysDiff = DateTime.Today.Subtract(birthday).Days
daysDiff / 365
Syntax difference:
Type annotations
class Person(string name, DateTime birthday) =
member this.Name =
name
member this.Birthday =
birthday
member this.Age() =
var daysDiff = DateTime.Today.Subtract(birthday).Days
daysDiff / 365
class Person(name: string, birthday: DateTime ) =
member this.Name =
name
member this.Birthday =
birthday
member this.Age() =
var daysDiff = DateTime.Today.Subtract(birthday).Days
daysDiff / 365
Syntax difference:
Different keywords
class Person(name: string, birthday: DateTime ) =
member this.Name =
name
member this.Birthday =
birthday
member this.Age() =
var daysDiff = DateTime.Today.Subtract(birthday).Days
daysDiff / 365
type Person(name: string, birthday: DateTime ) =
member this.Name =
name
member this.Birthday =
birthday
member this.Age() =
let daysDiff = DateTime.Today.Subtract(birthday).Days
daysDiff / 365
Compared with modern C#
class Person(string name, DateTime birthday)
{
public string Name { get; } = name;
public DateTime Birthday { get; } = birthday;
public int Age() =>
DateTime.Today.Subtract(birthday).Days / 365;
}
Modern C# equivalent with auto-properties
and expression-bodied members
Functional programming syntax
type Person = {
Name: string
Birthday: DateTime
}
let age person =
let daysDiff = DateTime.Today.Subtract(person.Birthday).Days
daysDiff / 365
// age : Person -> int
type Person = {
Name: string
Birthday: DateTime
}
let age person =
let daysDiff = DateTime.Today.Subtract(person.Birthday).Days
daysDiff / 365
Syntax is never the most important
thing about a programming language.
But…
Observation:
21 lines of code has shrunk
to 5 lines of code
You see 3x more
code on your
screen!
public class Person
{
public Person(string name, DateTime birthday)
{
_name = name;
_birthday = birthday;
}
private readonly string _name;
private readonly DateTime _birthday;
/// <summary>
/// Full name
/// </summary>
public string Name
{
get { return _name; }
}
/// <summary>
/// Birthday
/// </summary>
public DateTime Birthday
{
get { return _birthday; }
}
}
public class Person(string name, DateTime birthday) =
/// Full name
public string Name =
get { return name; }
/// Birthday
public DateTime Birthday =
get { return birthday; }
C#
F#
You write
1/3 as much code.
TYPE INFERENCE
Type inference
let doSomething f x =
let y = f (x + 1)
"hello" + y
Type inference
let doSomething f x =
let y = f (x + 1)
"hello" + y
Type inference
let doSomething f x =
let y = f (x + 1)
"hello" + y
Inferred type of doSomething :
f:(int -> string) -> x:int -> string
Type inference
// C# code
public IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
IEnumerable<TSource> source,
Func<TSource, TKey> keySelector
)
{
...
}
// F# code
let GroupBy source keySelector =
...
Benefits of type inference:
* Less typing
* Less noise, more logic
Here's a more complex example
DIFFERENT DEFAULTS
F# has different defaults
• Immutable by default
– mutable is special case
• Non-null types/classes by default
– Nullable is special case
• Structural equality by default
– reference equality is special case
• Everything must be initialized
Immutability by default
Mutability
let x = 1
x <- 2 // assign new value
Mutability
let mutable x = 1
x <- 2 // assign new value
Not nullable by default
Non null
type Person = {
Name: string
Birthday: DateTime
}
let x : Person = null
Non null
[<AllowNullLiteralAttribute>]
type Person(name: string, birthday: DateTime) =
member this.Name = name
member this.Birthday = birthday
let x : Person = null
Structural equality by default
(for record types)
Structural equality
type Person = {
Name: string
Birthday: DateTime
}
let bday = DateTime(1980,1,1)
let alice1 = {Name="Alice"; Birthday=bday}
let alice2 = {Name="Alice"; Birthday=bday}
alice1 = alice2 // true or false?
Everything must be initialized
Initialization
type Person = {
Name: string
Birthday: DateTime
}
let alice : Person
Initialization
type Person = {
Name: string
Birthday: DateTime
}
let alice = {Name="Alice"}
DIFFERENT PHILOSOPHY
Different philosophies
• C# historically comes from C-like approach.
• F# comes from ML, a MetaLanguage for
proving things.
Goal: Predictable code
• Can you understand the code using only the
information that you have right in front of you?
• You’re not allowed to delve into other parts of
the codebase!
Example 1
The answer is
"hello world".
What value is y?
var x = 1;
DoSomething(x);
var y = "hello " + x;
Example 1
function DoSomething (foo) { x = "world"; }
var x = 1;
DoSomething(x);
var y = "hello " + x;
Predictable code
C# is more predictable than JavaScript!
In C#, if you don't match up the types properly,
you get a compile-time error not a run-time error.
This is good!
How to make your language predictable:
• Variables should not be allowed to change their type
Example 2
// create two customers
var cust1 = new Customer(99, "J Smith");
var cust2 = new Customer(99, "J Smith");
// true or false?
cust1 == cust2;
How to make your language predictable:
• Variables should not be allowed to change their type
• Objects with the same values should be equal by
default.
Example 3
// create a customer and an order
var cust = new Customer(99, "J Smith");
var order = new Order(99, "J Smith");
// true or false?
cust.Equals(order);
How to make your language predictable:
• Variables should not be allowed to change their type
• Objects with the same values should be equal by
default.
• Comparing objects of different types is a compile-
time error.
Example 4
// create a customer
var cust = new Customer();
// what is the expected output?
Console.WriteLine(cust.Address.Country)
How to make your language predictable:
• Variables should not be allowed to change their type
• Objects with the same values should be equal by default.
• Comparing objects of different types is a compile-time error.
• Objects must always be initialized to a valid state. Not doing
so is a compile-time error.
Example 5
// create a customer
var cust = new Customer(99, "J Smith");
// add it to a set
var processedCustomers = new HashSet<Customer>();
processedCustomers.Add(cust);
// process it
ProcessCustomer(cust);
// Is the customer still in the set? True or false?
processedCustomers.Contains(cust);
You can't tell! Not predictable!
If ProcessCustomer mutates the customer, it
might change the hash 
Example 5
// create a customer
var cust = new ImmutableCustomer(99, "J Smith");
// add it to a set
var processedCustomers = new HashSet<ImmutableCustomer>();
processedCustomers.Add(cust);
// process it and return the changes
var changedCustomer = ProcessCustomer(cust);
// Is the customer still in the set? True or false?
processedCustomers.Contains(cust);
Immutability forces
changed values to be
returned explictly. Original
value unchanged.
How to make your language predictable:
• Variables should not be allowed to change their type
• Objects with the same values should be equal by default.
• Comparing objects of different types is a compile-time error.
• Objects must always be initialized to a valid state. Not doing
so is a compile-time error.
• Once created, objects and collections must be immutable.
Example 6
// create a repository
var repo = new CustomerRepository();
// find a customer by id
var customer = repo.GetById(42);
// what is the expected output?
Console.WriteLine(customer.Id);
What happens if the customer is missing?
Is the customer null or what?
You can't tell! Not predictable!
Example 6
// create a repository
var repo = new CustomerRepository();
// find a customer by id
var customerOrError = repo.GetById(42);
// handle both cases
if (customerOrError.IsCustomer)
Console.WriteLine(customerOrError.Customer.Id);
if (customerOrError.IsError)
Console.WriteLine(customerOrError.ErrorMessage);
Instead, build error cases into the return type.
How to make your language predictable:
• Variables should not be allowed to change their type
• Objects with the same values should be equal by default.
• Comparing objects of different types is a compile-time error.
• Objects must always be initialized to a valid state. Not doing
so is a compile-time error.
• Once created, objects and collections must be immutable.
• Missing data or errors must be made explicit. No nulls
allowed.
F# aims to be a predictable language:
• Variables are not be allowed to change their type
• Objects with the same values are equal by default.
• Comparing objects of different types is a compile-time error.
• Objects must be initialized to a valid state. Not doing so is a
compile-time error..
• Once created, objects and collections are (generally)
immutable.
• Missing data or errors are (generally) made explicit. Nulls are
a code smell.
FUNCTIONAL FIRST
Core principles of functional programming
Function
Parameterize all the things
Functions
Composition everywhere
FP Principle:
Functions are things
Function
Functions as things
The Tunnel of
Transformation
Function
apple -> banana
A function is a thing which
transforms inputs to outputs
Functions as things
let x = 1
let add x y = x + y
A function is a standalone thing,
not attached to a class
It can be used for inputs and outputs
of other functions
input
A function can be an output
A function is a standalone thing,
not attached to a class
It can be used for inputs and outputs
of other functions
output
input
A function can be an output
A function can be an input
A function is a standalone thing,
not attached to a class
It can be used for inputs and outputs
of other functions
output
input
input output
A function can be an output
A function can be an input
A function can be a parameter
A function is a standalone thing,
not attached to a class
It can be used for inputs and outputs
of other functions
output
input
input output
A function can be an output
A function can be an input
A function can be a parameter
A function is a standalone thing,
not attached to a class
It can be used for inputs and outputs
of other functions
From this simple foundation we can build complex systems
FP principle:
Composition everywhere
Function composition
Function 1
apple -> banana
Function 2
banana -> cherry
Function composition
>>
Function 1
apple -> banana
Function 2
banana -> cherry
Function composition
New Function
apple -> cherry
Can't tell it was built from
smaller functions!
Where did the banana go?
(abstraction)
add1 double5 12
let add1 x = x + 1
let double x = x + x
let add1_double =
add1 >> double
let x = add1_double 5
Composition (F#)
add1 double square5 144
let add1_double_square =
add1 >> double >> square
let x = add1_double_square 5
Composition (F#)
Func<int, int> add1 = x => x + 1;
Func<int, int> doubl = x => x + x;
Func<int, int> square = x => x * x;
var composed =
add1.Compose(doubl).Compose(square);
composed(5);
Composition (C#)
Piping (F#)
add1 5 // = 6
double (add1 5) // = 12
square (double (add1 5)) // = 144
5 |> add1 // = 6
5 |> add1 |> double // = 12
5 |> add1 |> double |> square // = 144
Standard way of nesting function calls can be confusing if too deep
add1 double square5 6 12 144
Piping (C#)
5.Pipe(Add1); // = 6
5.Pipe(Add1).Pipe(Double); // = 12
5.Pipe(Add1).Pipe(Double).Pipe(Square);
Func<int, int> add1 = x => x + 1;
Func<int, int> doubl = x => x + x;
Func<int, int> square = x => x * x;
add1 double square5 6 12 144
Why we say F# is "functional-first"
• F# makes FP easy
• C# makes FP possible
– but it's awkward and not idiomatic
FP Guideline:
Parameterize all the things
Parameterize all the things
let printList() =
for i in [1..10] do
printfn "the number is %i" i
Parameterize all the things
let printList aList =
for i in aList do
printfn "the number is %i" i
Parameterize all the things
let printList anAction aList =
for i in aList do
anAction i
FPers would parameterize the action as well:
We've decoupled the
behavior from the data.
Any list, any action!
Parameterize all the things
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;
}
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;
}
Parameterize all the things
Parameterize all the things
let fold action initialValue list =
let mutable totalSoFar = initialValue
for item in list do
totalSoFar <- action totalSoFar item
totalSoFar
Parameterize all the things
let fold action initialValue list =
let mutable totalSoFar = initialValue
for item in list do
totalSoFar <- action totalSoFar item
totalSoFar
Parameterize all the things
let product n =
let initialValue = 1
let action productSoFar x = productSoFar * x
[1..n] |> List.fold action initialValue
let sum n =
let initialValue = 0
let action sumSoFar x = sumSoFar+x
[1..n] |> List.fold action initialValue
Lots of collection functions like this:
"fold", "map", "reduce", "collect", etc.
Big topic! Not enough time right now !
More at fsharpforfunandprofit.com/fppatterns
ALGEBRAIC TYPE SYSTEM
What are F# types?
A type is not a class
What is a type?
A type is a just a name
for a set of things
Set of
valid inputs
Set of
valid outputs
Function
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
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
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
A type is a just a name
for a set of things
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
Set of
valid inputs
Set of
valid outputs
Function
This is a type
containing functions
A type is a just a name
for a set of things
F# types can be composed
"Algebraic type system"
F# for C# Programmers
New types are built from smaller types using:
“AND”
“OR”
Example: pairs, tuples, records
FruitSalad = One each of and and
“AND” types
type FruitSalad = {
Apple: AppleVariety
Banana: BananaVariety
Cherry: CherryVariety
}
Snack = or or
“OR” types
type Snack =
| Apple of AppleVariety
| Banana of BananaVariety
| Cherry of CherryVariety
Real world example
of type composition
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
interface IPaymentMethod
{..}
class Cash() : IPaymentMethod
{..}
class Check(int checkNo): IPaymentMethod
{..}
class Card(string cardType, string cardNo) : IPaymentMethod
{..}
In C# you would probably implement it as an
interface and a set of subclasses, like this:
type CheckNumber = int
type CardNumber = string
In F# you would probably implement by composing
types, like this
type CheckNumber = int
type CardNumber = string
type CardType = Visa | Mastercard
type CreditCardInfo = CardType * CardNumber
type CheckNumber = int
type CardNumber = string
type CardType = Visa | Mastercard
type CreditCardInfo = CardType * CardNumber
type PaymentMethod =
| Cash
| Check of CheckNumber
| Card of CreditCardInfo
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 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 }
F# design principle:
Types are executable documentation
type Deal = Deck –› (Deck * Card)
type PickupCard = (Hand * Card) –› Hand
Types are executable documentation
type Suit = Club | Diamond | Spade | Heart
type Rank = Two | Three | Four | Five | Six | Seven | Eight
| Nine |Ten | Jack | Queen | King | Ace
type Card = Suit * 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!
Types are executable documentation
type CardType =Visa | Mastercard
type CardNumber = CardNumber of string
type CheckNumber = CheckNumber of int
type PaymentMethod =
| Cash
| Check of CheckNumber
| Card of CardType * CardNumber
Another big topic and not enough time  
More on DDD and designing with types at
fsharpforfunandprofit.com/ddd
INTERACTIVITY
Interactivity demo
Slides and video here
F# consulting
fsharpforfunandprofit.com/csharp
F# for C# programmers

More Related Content

What's hot (20)

PPTX
Getting started with typescript
C...L, NESPRESSO, WAFAASSURANCE, SOFRECOM ORANGE
 
PPTX
Python programing
hamzagame
 
PDF
Domain Modeling Made Functional (KanDDDinsky 2019)
Scott Wlaschin
 
PDF
Introduction to Python Pandas for Data Analytics
Phoenix
 
PPT
Threads V4
Sunil OS
 
PPTX
Arrays In C Language
Surbhi Yadav
 
PDF
[COSCUP 2022] 讓黑畫面再次偉大 - 用 PHP 寫 CLI 工具
Shengyou Fan
 
PPTX
Typescript in 30mins
Udaya Kumar
 
PDF
Understanding CSS Selectors in Selenium.pdf
pCloudy
 
PPTX
Python idle introduction(3)
Fahad Ashrafi
 
PDF
The Power Of Composition (DotNext 2019)
Scott Wlaschin
 
PPTX
MySQL 5.7 String Functions
Francesco Marino
 
PPT
C++
Sunil OS
 
PDF
L'API Collector dans tous ses états
José Paumard
 
PDF
Clean code
Alvaro García Loaisa
 
PDF
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
Philip Schwarz
 
PDF
JavaScript guide 2020 Learn JavaScript
Laurence Svekis ✔
 
PPTX
Type script - advanced usage and practices
Iwan van der Kleijn
 
PDF
Clean code: meaningful Name
nahid035
 
PPTX
Loops in Python.pptx
Guru Nanak Dev University, Amritsar
 
Getting started with typescript
C...L, NESPRESSO, WAFAASSURANCE, SOFRECOM ORANGE
 
Python programing
hamzagame
 
Domain Modeling Made Functional (KanDDDinsky 2019)
Scott Wlaschin
 
Introduction to Python Pandas for Data Analytics
Phoenix
 
Threads V4
Sunil OS
 
Arrays In C Language
Surbhi Yadav
 
[COSCUP 2022] 讓黑畫面再次偉大 - 用 PHP 寫 CLI 工具
Shengyou Fan
 
Typescript in 30mins
Udaya Kumar
 
Understanding CSS Selectors in Selenium.pdf
pCloudy
 
Python idle introduction(3)
Fahad Ashrafi
 
The Power Of Composition (DotNext 2019)
Scott Wlaschin
 
MySQL 5.7 String Functions
Francesco Marino
 
L'API Collector dans tous ses états
José Paumard
 
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
Philip Schwarz
 
JavaScript guide 2020 Learn JavaScript
Laurence Svekis ✔
 
Type script - advanced usage and practices
Iwan van der Kleijn
 
Clean code: meaningful Name
nahid035
 

Similar to F# for C# Programmers (20)

PPT
Introduction-to-Csharpppppppppppppppp.ppt
kamalsmail1
 
PPT
Introduction to csharp
hmanjarawala
 
PPT
Introduction to csharp
voegtu
 
PPT
Introduction to csharp
voegtu
 
PPT
CSharp_03_ClassesStructs_and_introduction
Ranjithsingh20
 
PPTX
C# overview part 2
sagaroceanic11
 
PPTX
CSharp presentation and software developement
frwebhelp
 
PPTX
Can F# make us better as .NET developers?
Kevin Avignon
 
PDF
Introduction to c#
singhadarsh
 
PDF
Introduction To Csharp
sarfarazali
 
PPTX
C# - Igor Ralić
Software StartUp Academy Osijek
 
PPTX
F# as our day job by 2016
Tomas Jansson
 
PPTX
C# Today and Tomorrow
Bertrand Le Roy
 
PPT
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
NALESVPMEngg
 
PPT
Introduction-to-Csharp programacion orientada a objetos
KilbertChusiHuamani
 
PPT
Introduction-to-Csharp.ppt
Almamoon
 
PPT
Introduction-to-Csharp.ppt
mothertheressa
 
PPT
Introduction to-csharp
SDFG5
 
PPT
IntroToCSharpcode.ppt
psundarau
 
PPTX
5. c sharp language overview part ii
Svetlin Nakov
 
Introduction-to-Csharpppppppppppppppp.ppt
kamalsmail1
 
Introduction to csharp
hmanjarawala
 
Introduction to csharp
voegtu
 
Introduction to csharp
voegtu
 
CSharp_03_ClassesStructs_and_introduction
Ranjithsingh20
 
C# overview part 2
sagaroceanic11
 
CSharp presentation and software developement
frwebhelp
 
Can F# make us better as .NET developers?
Kevin Avignon
 
Introduction to c#
singhadarsh
 
Introduction To Csharp
sarfarazali
 
F# as our day job by 2016
Tomas Jansson
 
C# Today and Tomorrow
Bertrand Le Roy
 
Introduction to Csharp (C-Sharp) is a programming language developed by Micro...
NALESVPMEngg
 
Introduction-to-Csharp programacion orientada a objetos
KilbertChusiHuamani
 
Introduction-to-Csharp.ppt
Almamoon
 
Introduction-to-Csharp.ppt
mothertheressa
 
Introduction to-csharp
SDFG5
 
IntroToCSharpcode.ppt
psundarau
 
5. c sharp language overview part ii
Svetlin Nakov
 
Ad

More from Scott Wlaschin (19)

PDF
Domain Modeling Made Functional (DevTernity 2022)
Scott Wlaschin
 
PDF
Building confidence in concurrent code with a model checker: TLA+ for program...
Scott Wlaschin
 
PDF
Reinventing the Transaction Script (NDC London 2020)
Scott Wlaschin
 
PDF
The Functional Programmer's Toolkit (NDC London 2019)
Scott Wlaschin
 
PDF
The Functional Programming Toolkit (NDC Oslo 2019)
Scott Wlaschin
 
PDF
Four Languages From Forty Years Ago
Scott Wlaschin
 
PDF
The Power of Composition
Scott Wlaschin
 
PDF
Designing with capabilities (DDD-EU 2017)
Scott Wlaschin
 
PDF
Thirteen ways of looking at a turtle
Scott Wlaschin
 
PDF
Designing with Capabilities
Scott Wlaschin
 
PDF
Dr Frankenfunctor and the Monadster
Scott Wlaschin
 
PDF
Enterprise Tic-Tac-Toe
Scott Wlaschin
 
PDF
An introduction to property based testing
Scott Wlaschin
 
PDF
Functional Programming Patterns (NDC London 2014)
Scott Wlaschin
 
PDF
Functional Programming Patterns (BuildStuff '14)
Scott Wlaschin
 
PDF
Swift vs. Language X
Scott Wlaschin
 
PDF
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Scott Wlaschin
 
PDF
Doge-driven design
Scott Wlaschin
 
PDF
The Theory of Chains
Scott Wlaschin
 
Domain Modeling Made Functional (DevTernity 2022)
Scott Wlaschin
 
Building confidence in concurrent code with a model checker: TLA+ for program...
Scott Wlaschin
 
Reinventing the Transaction Script (NDC London 2020)
Scott Wlaschin
 
The Functional Programmer's Toolkit (NDC London 2019)
Scott Wlaschin
 
The Functional Programming Toolkit (NDC Oslo 2019)
Scott Wlaschin
 
Four Languages From Forty Years Ago
Scott Wlaschin
 
The Power of Composition
Scott Wlaschin
 
Designing with capabilities (DDD-EU 2017)
Scott Wlaschin
 
Thirteen ways of looking at a turtle
Scott Wlaschin
 
Designing with Capabilities
Scott Wlaschin
 
Dr Frankenfunctor and the Monadster
Scott Wlaschin
 
Enterprise Tic-Tac-Toe
Scott Wlaschin
 
An introduction to property based testing
Scott Wlaschin
 
Functional Programming Patterns (NDC London 2014)
Scott Wlaschin
 
Functional Programming Patterns (BuildStuff '14)
Scott Wlaschin
 
Swift vs. Language X
Scott Wlaschin
 
Domain Driven Design with the F# type System -- F#unctional Londoners 2014
Scott Wlaschin
 
Doge-driven design
Scott Wlaschin
 
The Theory of Chains
Scott Wlaschin
 
Ad

Recently uploaded (20)

PDF
NEW-Viral>Wondershare Filmora 14.5.18.12900 Crack Free
sherryg1122g
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
AOMEI Partition Assistant Crack 10.8.2 + WinPE Free Downlaod New Version 2025
bashirkhan333g
 
PPTX
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
PPTX
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
Technical-Careers-Roadmap-in-Software-Market.pdf
Hussein Ali
 
PDF
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PDF
MiniTool Power Data Recovery 8.8 With Crack New Latest 2025
bashirkhan333g
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
NEW-Viral>Wondershare Filmora 14.5.18.12900 Crack Free
sherryg1122g
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
AOMEI Partition Assistant Crack 10.8.2 + WinPE Free Downlaod New Version 2025
bashirkhan333g
 
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
Technical-Careers-Roadmap-in-Software-Market.pdf
Hussein Ali
 
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
MiniTool Power Data Recovery 8.8 With Crack New Latest 2025
bashirkhan333g
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 

F# for C# Programmers

  • 1. F# for C# programmers @ScottWlaschin fsharpforfunandprofit.com
  • 2. A language that doesn't affect the way you think about programming, is not worth knowing – Alan Perlis
  • 3. “F# is slightly better than C#, but not so much that it's really worth the effort to move towards it.” “Learning F# was one of the biggest boosts in my career as a C# developer. I don't use it professionally (I wish I could) but this knowledge made me a better programmer.”
  • 4. About F# • Developed by Microsoft Research – Shipped withVisual Studio in 2010 • Open source – On github • Cross platform – Works withVS Code (and other editors) • Very active and friendly community. – Start with fsharp.org – F# Slack channel – #fsharp onTwitter
  • 5. A tour of F# • Differences between C# and F# – Concise syntax – Type inference – Different defaults – Different philosophy • Special to F# – Functional-first – Algebraic type system – Interactivity From least to most important!
  • 7. public class Person { public Person(string name, DateTime birthday) { _name = name; _birthday = birthday; } private readonly string _name; private readonly DateTime _birthday; public string Name { get { return _name; } } public DateTime Birthday { get { return _birthday; } } }
  • 9. public class Person { public Person(string name, DateTime birthday) { _name = name; _birthday = birthday; } private readonly string _name; private readonly DateTime _birthday; public string Name { get { return _name; } } public DateTime Birthday { get { return _birthday; } } } Do we really need the braces? The indentation already gives us all the clues we need.
  • 10. public class Person { public Person(string name, DateTime birthday) { _name = name; _birthday = birthday; } private readonly string _name; private readonly DateTime _birthday; public string Name { get { return _name; } } public DateTime Birthday { get { return _birthday; } } } Example where braces indicate blocks
  • 11. public class Person = public Person(string name, DateTime birthday) = _name = name; _birthday = birthday; private readonly string _name; private readonly DateTime _birthday; public string Name = get { return _name; } public DateTime Birthday = get { return _birthday; } Example where indentation indicates blocks Is it really that much harder to read?
  • 12. public class Person = public Person(string name, DateTime birthday) = _name = name; _birthday = birthday; private readonly string _name; private readonly DateTime _birthday; public string Name = get { return _name; } public DateTime Birthday = get { return _birthday; } Use '=' to start blocks
  • 13. public class Person = public Person(string name, DateTime birthday) = _name = name; _birthday = birthday; private readonly string _name; private readonly DateTime _birthday; public string Name = get { return _name; } public DateTime Birthday = get { return _birthday; } Shift up to use less vertical space
  • 14. People who complain about using a language with syntactic whitespace People who have spent time using a language with syntactic whitespace "Oddly enough, Python's use of whitespace stopped feeling unnatural after about twenty minutes. I just indented code, pretty much as I would have done in a C program anyway, and it worked." - Eric Raymond HelpfulVenn Diagram Overlap
  • 15. Syntax difference: Automatically create backing fields from constructor parameters
  • 16. public class Person = public Person(string name, DateTime birthday) = _name = name; _birthday = birthday; private readonly string _name; private readonly DateTime _birthday; public string Name = get { return _name; } public DateTime Birthday = get { return _birthday; } A lot of duplication...
  • 17. public class Person = public Person(string name, DateTime birthday) = ... public string Name = get { return name; } public DateTime Birthday = get { return birthday; } Use the constructor params directly
  • 18. Syntax difference: Merge the primary constructor with the class definition
  • 19. public class Person = public Person(string name, DateTime birthday) = ... public string Name = get { return name; } public DateTime Birthday = get { return birthday; } How often do you have more than one constructor?
  • 20. public class Person(string name, DateTime birthday) = public string Name = get { return name; } public DateTime Birthday = get { return birthday; }
  • 22. public class Person(string name, DateTime birthday) = public string Name = get { return name; } public DateTime Birthday = get { return birthday; } So why use ‘get’? The class is immutable. Every property is "get" only.
  • 23. public class Person(string name, DateTime birthday) = public string Name = return name; public DateTime Birthday = return birthday; 'get' is gone!
  • 24. public class Person(string name, DateTime birthday) = public string Name = return name; public DateTime Birthday = return birthday; Who even likes typing semicolons anyway?
  • 25. public class Person(string name, DateTime birthday) = public string Name = return name public DateTime Birthday = return birthday Semicolons gone!
  • 27. public class Person(string name, DateTime birthday) = public string Name = return name public DateTime Birthday = return birthday
  • 28. public class Person(string name, DateTime birthday) = public string Name = name public DateTime Birthday = birthday F# is an expression- oriented language
  • 30. public class Person(string name, DateTime birthday) = public string Name = name public DateTime Birthday = birthday
  • 31. class Person(string name, DateTime birthday) = string Name = name DateTime Birthday = birthday
  • 33. class Person(string name, DateTime birthday) = string Name = name DateTime Birthday = birthday Why do we have to repeat the type? Can't the compiler figure it out for us?
  • 34. class Person(string name, DateTime birthday) = Name = name Birthday = birthday
  • 35. class Person(string name, DateTime birthday) = member this.Name = name member this.Birthday = birthday
  • 36. class Person(string name, DateTime birthday) = member this.Name = name member this.Birthday = birthday member this.Age() = var daysDiff = DateTime.Today.Subtract(birthday).Days daysDiff / 365
  • 38. class Person(string name, DateTime birthday) = member this.Name = name member this.Birthday = birthday member this.Age() = var daysDiff = DateTime.Today.Subtract(birthday).Days daysDiff / 365
  • 39. class Person(name: string, birthday: DateTime ) = member this.Name = name member this.Birthday = birthday member this.Age() = var daysDiff = DateTime.Today.Subtract(birthday).Days daysDiff / 365
  • 41. class Person(name: string, birthday: DateTime ) = member this.Name = name member this.Birthday = birthday member this.Age() = var daysDiff = DateTime.Today.Subtract(birthday).Days daysDiff / 365
  • 42. type Person(name: string, birthday: DateTime ) = member this.Name = name member this.Birthday = birthday member this.Age() = let daysDiff = DateTime.Today.Subtract(birthday).Days daysDiff / 365
  • 44. class Person(string name, DateTime birthday) { public string Name { get; } = name; public DateTime Birthday { get; } = birthday; public int Age() => DateTime.Today.Subtract(birthday).Days / 365; } Modern C# equivalent with auto-properties and expression-bodied members
  • 46. type Person = { Name: string Birthday: DateTime } let age person = let daysDiff = DateTime.Today.Subtract(person.Birthday).Days daysDiff / 365
  • 47. // age : Person -> int type Person = { Name: string Birthday: DateTime } let age person = let daysDiff = DateTime.Today.Subtract(person.Birthday).Days daysDiff / 365
  • 48. Syntax is never the most important thing about a programming language. But…
  • 49. Observation: 21 lines of code has shrunk to 5 lines of code
  • 50. You see 3x more code on your screen!
  • 51. public class Person { public Person(string name, DateTime birthday) { _name = name; _birthday = birthday; } private readonly string _name; private readonly DateTime _birthday; /// <summary> /// Full name /// </summary> public string Name { get { return _name; } } /// <summary> /// Birthday /// </summary> public DateTime Birthday { get { return _birthday; } } } public class Person(string name, DateTime birthday) = /// Full name public string Name = get { return name; } /// Birthday public DateTime Birthday = get { return birthday; } C# F# You write 1/3 as much code.
  • 53. Type inference let doSomething f x = let y = f (x + 1) "hello" + y
  • 54. Type inference let doSomething f x = let y = f (x + 1) "hello" + y
  • 55. Type inference let doSomething f x = let y = f (x + 1) "hello" + y Inferred type of doSomething : f:(int -> string) -> x:int -> string
  • 56. Type inference // C# code public IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>( IEnumerable<TSource> source, Func<TSource, TKey> keySelector ) { ... } // F# code let GroupBy source keySelector = ... Benefits of type inference: * Less typing * Less noise, more logic Here's a more complex example
  • 58. F# has different defaults • Immutable by default – mutable is special case • Non-null types/classes by default – Nullable is special case • Structural equality by default – reference equality is special case • Everything must be initialized
  • 60. Mutability let x = 1 x <- 2 // assign new value
  • 61. Mutability let mutable x = 1 x <- 2 // assign new value
  • 62. Not nullable by default
  • 63. Non null type Person = { Name: string Birthday: DateTime } let x : Person = null
  • 64. Non null [<AllowNullLiteralAttribute>] type Person(name: string, birthday: DateTime) = member this.Name = name member this.Birthday = birthday let x : Person = null
  • 65. Structural equality by default (for record types)
  • 66. Structural equality type Person = { Name: string Birthday: DateTime } let bday = DateTime(1980,1,1) let alice1 = {Name="Alice"; Birthday=bday} let alice2 = {Name="Alice"; Birthday=bday} alice1 = alice2 // true or false?
  • 67. Everything must be initialized
  • 68. Initialization type Person = { Name: string Birthday: DateTime } let alice : Person
  • 69. Initialization type Person = { Name: string Birthday: DateTime } let alice = {Name="Alice"}
  • 71. Different philosophies • C# historically comes from C-like approach. • F# comes from ML, a MetaLanguage for proving things.
  • 72. Goal: Predictable code • Can you understand the code using only the information that you have right in front of you? • You’re not allowed to delve into other parts of the codebase!
  • 73. Example 1 The answer is "hello world". What value is y? var x = 1; DoSomething(x); var y = "hello " + x;
  • 74. Example 1 function DoSomething (foo) { x = "world"; } var x = 1; DoSomething(x); var y = "hello " + x;
  • 75. Predictable code C# is more predictable than JavaScript! In C#, if you don't match up the types properly, you get a compile-time error not a run-time error. This is good!
  • 76. How to make your language predictable: • Variables should not be allowed to change their type
  • 77. Example 2 // create two customers var cust1 = new Customer(99, "J Smith"); var cust2 = new Customer(99, "J Smith"); // true or false? cust1 == cust2;
  • 78. How to make your language predictable: • Variables should not be allowed to change their type • Objects with the same values should be equal by default.
  • 79. Example 3 // create a customer and an order var cust = new Customer(99, "J Smith"); var order = new Order(99, "J Smith"); // true or false? cust.Equals(order);
  • 80. How to make your language predictable: • Variables should not be allowed to change their type • Objects with the same values should be equal by default. • Comparing objects of different types is a compile- time error.
  • 81. Example 4 // create a customer var cust = new Customer(); // what is the expected output? Console.WriteLine(cust.Address.Country)
  • 82. How to make your language predictable: • Variables should not be allowed to change their type • Objects with the same values should be equal by default. • Comparing objects of different types is a compile-time error. • Objects must always be initialized to a valid state. Not doing so is a compile-time error.
  • 83. Example 5 // create a customer var cust = new Customer(99, "J Smith"); // add it to a set var processedCustomers = new HashSet<Customer>(); processedCustomers.Add(cust); // process it ProcessCustomer(cust); // Is the customer still in the set? True or false? processedCustomers.Contains(cust); You can't tell! Not predictable! If ProcessCustomer mutates the customer, it might change the hash 
  • 84. Example 5 // create a customer var cust = new ImmutableCustomer(99, "J Smith"); // add it to a set var processedCustomers = new HashSet<ImmutableCustomer>(); processedCustomers.Add(cust); // process it and return the changes var changedCustomer = ProcessCustomer(cust); // Is the customer still in the set? True or false? processedCustomers.Contains(cust); Immutability forces changed values to be returned explictly. Original value unchanged.
  • 85. How to make your language predictable: • Variables should not be allowed to change their type • Objects with the same values should be equal by default. • Comparing objects of different types is a compile-time error. • Objects must always be initialized to a valid state. Not doing so is a compile-time error. • Once created, objects and collections must be immutable.
  • 86. Example 6 // create a repository var repo = new CustomerRepository(); // find a customer by id var customer = repo.GetById(42); // what is the expected output? Console.WriteLine(customer.Id); What happens if the customer is missing? Is the customer null or what? You can't tell! Not predictable!
  • 87. Example 6 // create a repository var repo = new CustomerRepository(); // find a customer by id var customerOrError = repo.GetById(42); // handle both cases if (customerOrError.IsCustomer) Console.WriteLine(customerOrError.Customer.Id); if (customerOrError.IsError) Console.WriteLine(customerOrError.ErrorMessage); Instead, build error cases into the return type.
  • 88. How to make your language predictable: • Variables should not be allowed to change their type • Objects with the same values should be equal by default. • Comparing objects of different types is a compile-time error. • Objects must always be initialized to a valid state. Not doing so is a compile-time error. • Once created, objects and collections must be immutable. • Missing data or errors must be made explicit. No nulls allowed.
  • 89. F# aims to be a predictable language: • Variables are not be allowed to change their type • Objects with the same values are equal by default. • Comparing objects of different types is a compile-time error. • Objects must be initialized to a valid state. Not doing so is a compile-time error.. • Once created, objects and collections are (generally) immutable. • Missing data or errors are (generally) made explicit. Nulls are a code smell.
  • 91. Core principles of functional programming Function Parameterize all the things Functions Composition everywhere
  • 92. FP Principle: Functions are things Function
  • 93. Functions as things The Tunnel of Transformation Function apple -> banana A function is a thing which transforms inputs to outputs
  • 94. Functions as things let x = 1 let add x y = x + y
  • 95. A function is a standalone thing, not attached to a class It can be used for inputs and outputs of other functions
  • 96. input A function can be an output A function is a standalone thing, not attached to a class It can be used for inputs and outputs of other functions
  • 97. output input A function can be an output A function can be an input A function is a standalone thing, not attached to a class It can be used for inputs and outputs of other functions
  • 98. output input input output A function can be an output A function can be an input A function can be a parameter A function is a standalone thing, not attached to a class It can be used for inputs and outputs of other functions
  • 99. output input input output A function can be an output A function can be an input A function can be a parameter A function is a standalone thing, not attached to a class It can be used for inputs and outputs of other functions From this simple foundation we can build complex systems
  • 101. Function composition Function 1 apple -> banana Function 2 banana -> cherry
  • 102. Function composition >> Function 1 apple -> banana Function 2 banana -> cherry
  • 103. Function composition New Function apple -> cherry Can't tell it was built from smaller functions! Where did the banana go? (abstraction)
  • 104. add1 double5 12 let add1 x = x + 1 let double x = x + x let add1_double = add1 >> double let x = add1_double 5 Composition (F#)
  • 105. add1 double square5 144 let add1_double_square = add1 >> double >> square let x = add1_double_square 5 Composition (F#)
  • 106. Func<int, int> add1 = x => x + 1; Func<int, int> doubl = x => x + x; Func<int, int> square = x => x * x; var composed = add1.Compose(doubl).Compose(square); composed(5); Composition (C#)
  • 108. add1 5 // = 6 double (add1 5) // = 12 square (double (add1 5)) // = 144 5 |> add1 // = 6 5 |> add1 |> double // = 12 5 |> add1 |> double |> square // = 144 Standard way of nesting function calls can be confusing if too deep add1 double square5 6 12 144
  • 110. 5.Pipe(Add1); // = 6 5.Pipe(Add1).Pipe(Double); // = 12 5.Pipe(Add1).Pipe(Double).Pipe(Square); Func<int, int> add1 = x => x + 1; Func<int, int> doubl = x => x + x; Func<int, int> square = x => x * x; add1 double square5 6 12 144
  • 111. Why we say F# is "functional-first" • F# makes FP easy • C# makes FP possible – but it's awkward and not idiomatic
  • 113. Parameterize all the things let printList() = for i in [1..10] do printfn "the number is %i" i
  • 114. Parameterize all the things let printList aList = for i in aList do printfn "the number is %i" i
  • 115. Parameterize all the things let printList anAction aList = for i in aList do anAction i FPers would parameterize the action as well: We've decoupled the behavior from the data. Any list, any action!
  • 116. Parameterize all the things 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; }
  • 117. 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; } Parameterize all the things
  • 118. Parameterize all the things let fold action initialValue list = let mutable totalSoFar = initialValue for item in list do totalSoFar <- action totalSoFar item totalSoFar
  • 119. Parameterize all the things let fold action initialValue list = let mutable totalSoFar = initialValue for item in list do totalSoFar <- action totalSoFar item totalSoFar
  • 120. Parameterize all the things let product n = let initialValue = 1 let action productSoFar x = productSoFar * x [1..n] |> List.fold action initialValue let sum n = let initialValue = 0 let action sumSoFar x = sumSoFar+x [1..n] |> List.fold action initialValue Lots of collection functions like this: "fold", "map", "reduce", "collect", etc.
  • 121. Big topic! Not enough time right now ! More at fsharpforfunandprofit.com/fppatterns
  • 123. What are F# types? A type is not a class
  • 124. What is a type? A type is a just a name for a set of things Set of valid inputs Set of valid outputs Function
  • 125. 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
  • 126. 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
  • 127. 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 A type is a just a name for a set of things
  • 128. 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
  • 129. Set of valid inputs Set of valid outputs Function This is a type containing functions A type is a just a name for a set of things
  • 130. F# types can be composed "Algebraic type system"
  • 132. New types are built from smaller types using: “AND” “OR”
  • 133. Example: pairs, tuples, records FruitSalad = One each of and and “AND” types type FruitSalad = { Apple: AppleVariety Banana: BananaVariety Cherry: CherryVariety }
  • 134. Snack = or or “OR” types type Snack = | Apple of AppleVariety | Banana of BananaVariety | Cherry of CherryVariety
  • 135. Real world example of type composition
  • 136. 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
  • 137. interface IPaymentMethod {..} class Cash() : IPaymentMethod {..} class Check(int checkNo): IPaymentMethod {..} class Card(string cardType, string cardNo) : IPaymentMethod {..} In C# you would probably implement it as an interface and a set of subclasses, like this:
  • 138. type CheckNumber = int type CardNumber = string In F# you would probably implement by composing types, like this
  • 139. type CheckNumber = int type CardNumber = string type CardType = Visa | Mastercard type CreditCardInfo = CardType * CardNumber
  • 140. type CheckNumber = int type CardNumber = string type CardType = Visa | Mastercard type CreditCardInfo = CardType * CardNumber type PaymentMethod = | Cash | Check of CheckNumber | Card of CreditCardInfo
  • 141. 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
  • 142. 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 }
  • 143. F# design principle: Types are executable documentation
  • 144. type Deal = Deck –› (Deck * Card) type PickupCard = (Hand * Card) –› Hand Types are executable documentation type Suit = Club | Diamond | Spade | Heart type Rank = Two | Three | Four | Five | Six | Seven | Eight | Nine |Ten | Jack | Queen | King | Ace type Card = Suit * 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!
  • 145. Types are executable documentation type CardType =Visa | Mastercard type CardNumber = CardNumber of string type CheckNumber = CheckNumber of int type PaymentMethod = | Cash | Check of CheckNumber | Card of CardType * CardNumber
  • 146. Another big topic and not enough time   More on DDD and designing with types at fsharpforfunandprofit.com/ddd
  • 149. Slides and video here F# consulting fsharpforfunandprofit.com/csharp F# for C# programmers