SlideShare a Scribd company logo
Hello!
I am Mikhail Shilkov
I am here to talk some Functional Programming and F#
You can nd me at @MikhailShilkov and http://mikhail.io
Poll
Agenda
Learn Functional Programming - 45 min
Learn F# - 30 min
Functional
Programming
Here's how it works
Principles
Constraints
around your
code
Bene잷�ts
Useful
properties that
hold under
these
constraints
Adoption
See where
these bene ts
make the
di erence
Principles
How is functional programming di erent?
Purity
Function as mapping
Domain Codomain
Determinism
// This is not deterministic 
public bool IsMoreThanHourAgo(DateTime time) 
{          
  var hour = TimeSpan.FromHours(‐1); 
  return time < DateTime.Now.Add(hour); 
} 
Determinism
// This is deterministic 
public bool IsMoreThanHourApart(DateTime time, DateTime anotherTime) 
{          
  var hour = TimeSpan.FromHours(‐1); 
  return time < anotherTime.Add(hour); 
} 
No side effects
public class TextCounter 
{ 
  private int wordCount = 0; 
  private int charCount = 0; 
 
  public void Count(string word) 
  { 
    this.WordCount += 1; 
    this.CharCount += word.Length; 
  } 
 
  public void Print() => 
    Console.WriteLine($"Words: {wordCount}, characters: {charCount}"); 
}
No side effects
public class TextCounter 
{ 
  public Tuple<int, int> Count(string[] word) 
  { 
    var wordCount = word.Length; 
    var charCount = word.Sum(w => w.Length); 
    return Tuple.Create(wordCount, charCount); 
  } 
}
Immutability
var importantThing = /*...*/; 
var result = DoWork(importantThing); 
// Can I trust my importantThing is unchanged?
Totality
One more function
Int Int
What's wrong here?
Int Int
public static int sqrtPlus1(int x) 
{ 
   if (x < 0) throw new ArgumentException(nameof(x)); 
   return Math.Floor(Math.Sqrt(x)) + 1; 
} 
Natural Int
Int Complex
No Exceptions for control flow
public static int sqrtPlus1(int x) 
{ 
   if (x < 0) throw new ArgumentException(nameof(x)); 
   return Math.Floor(Math.Sqrt(x)) + 1; 
} 
Strong type
system
Everything is a type
Primitive types
Int 
String
Algebraic Data Types
Int  * Int 
Byte * Boolean               
Int  | String 
Byte | Boolean
Function Types
Int ‐> Int 
Int[] ‐> String 
Int ‐> Int ‐> Int 
(Int ‐> Int ‐> Int) ‐> Int[] ‐> Int
Generics
T ‐> U 
`a[] ‐> `b
Side effects
unit 
String ‐> unit 
IO[T]
No NULLs
public interface IGetThing 
{ 
    // Can the result be null? 
    Thing Get(int id); 
} 
No NULLs
public interface IGetThing 
{ 
    // Hey, result is optional 
    Option<Thing> Get(int id); 
} 
Making invalid states
unrepresentable
public class Contact  
{ 
  public string Name { get; set; } 
  public EmailInfo Email { get; set; } 
  public AddressInfo Postal { get; set; } 
}
Making invalid states
unrepresentable
type ContactInfo =  
  | EmailOnly of EmailInfo 
  | PostOnly of AddressInfo 
  | EmailAndPost of EmailInfo * AddressInfo 
 
type Contact = { 
  Name: string; 
  Contact: ContactInfo; 
}
Benefits
Why do we want functional programming?
Formal reasoning
Referencial transparency
sqrt(mult2(add3(5)) 
sqrt(mult2(8)) 
sqrt(16) 
4 
Control Flow Expression Evaluation
Type signature as documentation
int ‐> int 
Customer ‐> Address 
U ‐> T[] ‐> U 
Identifier ‐> Task<Customer>
Composition
Succinct, concise and precise code
Higher Order Functions
var categories = products 
    .GroupBy(prod => prod.Category) 
    .Select(prodGroup => new {
        prodGroup,  
        minPrice = prodGroup.Min(p => p.UnitPrice) 
    }) 
    .Select(t => new { 
        Category = t.prodGroup.Key,  
        CheapestProducts = t.prodGroup 
            .Where(p => p.UnitPrice == t.minPrice) 
    });
Recursion
qsort [] = []  
qsort [a] = [a]  
qsort (a:as) = let (lesser, greater) = partition a as 
               in qsort lesser ++ [a] ++ qsort greater
Parallelism
Testabilty
Pure function is the easiest thing to
test
Functions are intrinsically mockable
Parameterized testing
[Test] 
public void MyTestCase() 
{ 
    var a = 5; 
    var b = 10; 
     
    var result = target.Add(a, b); 
    result.Should().Be(15); 
} 
Parameterized testing
[TestCase(5, 10, 15)] 
[TestCase(2, 3, 5)] 
[TestCase(‐2, 2, 0)] 
public void MyTestCase(int a, int b, int c) 
{ 
    var result = target.Add(a, b); 
    result.Should().Be(c); 
} 
Property-based testing
[Property] 
public void AddToZeroDoesNotChangeTheNumber(int a) 
{ 
    var result = target.Add(a, 0); 
    result.Should().Be(a); 
} 
 
[Property] 
public void OrderDoesNotMatter(int a, int b) 
{ 
    var result1 = target.Add(a, b); 
    var result2 = target.Add(b, a); 
    result1.Should().Be(result2); 
}
Adoption
Do people use FP in modern applications?
Your code should better be
SOLID!
public class FileStore : IMessageQuery 
{ 
  private readonly DirectoryInfo workingDirectory; 
   
  public FileStore(DirectoryInfo workingDirectory) 
  {          
    this.workingDirectory = workingDirectory; 
  }      
  public string Read(int id) 
  {          
    var path = Path.Combine( 
      this.workingDirectory.FullName,  
      id + ".txt"); 
    return File.ReadAllText(path); 
  }  
} 
Introduction of Functional Programming
Domain Driven Design
Event Sourcing
Event  
 
E
data
Projection  
 
P
data
Event handler
 
E[] -> P
function
Event
 
 
E
data
Command
 
 
C
data
Command
handler
 
C -> E[]
function
Actor Frameworks
Akka Streams
val counterRunnableGraph: RunnableGraph[Future[Int]] = 
  tweetsInMinuteFromNow 
    .filter(_.hashtags contains akkaTag) 
    .map(t => 1) 
    .toMat(sumSink)(Keep.right)
Apache Hadoop / MapReduce
Apache Hadoop / MapReduce
// This class performs the map operation, translating raw input into the key‐value 
// pairs we will feed into our reduce operation. 
class TokenizerMapper extends Mapper[Object,Text,Text,IntWritable] { 
  val one = new IntWritable(1) 
  val word = new Text 
   
  override 
  def map(key:Object, value:Text, context:Mapper[Object,Text,Text,IntWritable]#Context) = { 
    for (t <‐  value.toString().split("s")) { 
      word.set(t) 
      context.write(word, one) 
    } 
  } 
} 
   
// This class performs the reduce operation, iterating over the key‐value pairs 
// produced by our map operation to produce a result. In this case we just 
// calculate a simple total for each word seen. 
class IntSumReducer extends Reducer[Text,IntWritable,Text,IntWritable] { 
  override 
  def reduce(key:Text, values:java.lang.Iterable[IntWritable], context:Reducer[Text,IntWritable,Text,IntWritable]#Context) = { 
    val sum = values.foldLeft(0) { (t,i) => t + i.get } 
    context.write(key, new IntWritable(sum)) 
  } 
} 
   
// This class configures and runs the job with the map and reduce classes we've 
// specified above. 
object WordCount { 
  def main(args:Array[String]):Int = { 
    val job = new Job(conf, "word count") 
    job.setJarByClass(classOf[TokenizerMapper]) 
    job.setMapperClass(classOf[TokenizerMapper]) 
    job.setCombinerClass(classOf[IntSumReducer]) 
    job.setReducerClass(classOf[IntSumReducer]) 
    job.setOutputKeyClass(classOf[Text]) 
    job.setOutputValueClass(classOf[IntWritable]) 
    FileInputFormat.addInputPath(job, new Path(args(0))) 
    FileOutputFormat.setOutputPath(job, new Path((args(1)))) 
    if (job.waitForCompletion(true)) 0 else 1 
  } 
}
Apache Spark
Apache Spark
val sc = new SparkContext(conf) 
val input =  sc.textFile(inputFile) 
val words = input.flatMap(line => line.split(" ")) 
val counts = words.map(word => (word, 1)) 
                  .reduceByKey{case (x, y) => x + y} 
counts.saveAsTextFile(outputFile)
Apache Kafka
Wrapping Up
Functional Programming is...
Thanks!
Mikhail Shilkov
Next: Introduction of F#
You can nd me at @MikhailShilkov and http://mikhail.io

More Related Content

PPTX
Functional Programming Fundamentals
PDF
Introduction to functional programming
PDF
Functional Python Webinar from October 22nd, 2014
PDF
Introduction to functional programming (In Arabic)
PDF
CS4200 2019 | Lecture 2 | syntax-definition
PDF
Python functional programming
PDF
Functional go
PDF
Compiler Construction | Lecture 12 | Virtual Machines
Functional Programming Fundamentals
Introduction to functional programming
Functional Python Webinar from October 22nd, 2014
Introduction to functional programming (In Arabic)
CS4200 2019 | Lecture 2 | syntax-definition
Python functional programming
Functional go
Compiler Construction | Lecture 12 | Virtual Machines

What's hot (20)

PDF
CS4200 2019 | Lecture 4 | Syntactic Services
PDF
Python Programming - VII. Customizing Classes and Operator Overloading
PDF
Designing Architecture-aware Library using Boost.Proto
PDF
C++ questions And Answer
PDF
Compiler Construction | Lecture 6 | Introduction to Static Analysis
PPT
C Basics
PDF
Automatic Task-based Code Generation for High Performance DSEL
PDF
Python Programming - IX. On Randomness
PPT
Python Part 1
PDF
Compiler Construction | Lecture 8 | Type Constraints
PDF
Data types in c++
PDF
C programming & data structure [arrays & pointers]
DOC
Datastructure notes
PDF
Boost.Dispatch
PDF
Introduction to C++
PDF
Object Oriented Programming using C++ Part III
PPTX
Introduction to c++
PDF
Functional Programming in R
PDF
CBSE Question Paper Computer Science with C++ 2011
CS4200 2019 | Lecture 4 | Syntactic Services
Python Programming - VII. Customizing Classes and Operator Overloading
Designing Architecture-aware Library using Boost.Proto
C++ questions And Answer
Compiler Construction | Lecture 6 | Introduction to Static Analysis
C Basics
Automatic Task-based Code Generation for High Performance DSEL
Python Programming - IX. On Randomness
Python Part 1
Compiler Construction | Lecture 8 | Type Constraints
Data types in c++
C programming & data structure [arrays & pointers]
Datastructure notes
Boost.Dispatch
Introduction to C++
Object Oriented Programming using C++ Part III
Introduction to c++
Functional Programming in R
CBSE Question Paper Computer Science with C++ 2011
Ad

Viewers also liked (20)

PDF
The taste of F#
PDF
Functional Programming Patterns (NDC London 2014)
PDF
Dr Frankenfunctor and the Monadster
PPT
Introduction to programing languages part 1
PPT
13 A Programing Languages (IT) Lecture Slide
PPT
Lect 1. introduction to programming languages
DOCX
Glosario de-términos-especificos-utilizados-en-la-red-5-oct-16
PPTX
Go programing language
PPTX
program development and paradigms
PPTX
Futuristic programing language
PPTX
Science and software development
PDF
Describe professional programing languages and talks
PPT
Intro To Programming Concepts
PDF
Intro to functional programming
PDF
Streaming ETL With Akka.NET
PPTX
Introduction of c programming
PDF
Distributed Transactions in Akka.NET
PPTX
Programming Languages
PPT
Generations Of Programming Languages
PPTX
Programming Paradigm & Languages
The taste of F#
Functional Programming Patterns (NDC London 2014)
Dr Frankenfunctor and the Monadster
Introduction to programing languages part 1
13 A Programing Languages (IT) Lecture Slide
Lect 1. introduction to programming languages
Glosario de-términos-especificos-utilizados-en-la-red-5-oct-16
Go programing language
program development and paradigms
Futuristic programing language
Science and software development
Describe professional programing languages and talks
Intro To Programming Concepts
Intro to functional programming
Streaming ETL With Akka.NET
Introduction of c programming
Distributed Transactions in Akka.NET
Programming Languages
Generations Of Programming Languages
Programming Paradigm & Languages
Ad

Similar to Introduction of Functional Programming (20)

PDF
Functions in Pythons UDF and Functions Concepts
PPTX
SoCal Code Camp 2015: An introduction to Java 8
PDF
Twins: Object Oriented Programming and Functional Programming
PDF
01a-Introduction. pds.pdf
PDF
TWINS: OOP and FP - Warburton
PDF
oop-slides.pdf 01-introduction OOPS concepts in C++ JAVA
PDF
Twins: OOP and FP
PDF
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
PPT
U19CS101 - PPS Unit 4 PPT (1).ppt
ODP
PHP Barcelona 2010 - Architecture and testability
PPTX
Vendredi Tech_ la programmation fonctionnelle.pptx
PPT
Fpga 13-task-and-functions
PDF
Software Engineering Best Practices @ Nylas
PDF
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
PPTX
Getting Started with Test-Driven Development at Longhorn PHP 2023
PPTX
Android design patterns
PDF
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
Functions in Pythons UDF and Functions Concepts
SoCal Code Camp 2015: An introduction to Java 8
Twins: Object Oriented Programming and Functional Programming
01a-Introduction. pds.pdf
TWINS: OOP and FP - Warburton
oop-slides.pdf 01-introduction OOPS concepts in C++ JAVA
Twins: OOP and FP
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
U19CS101 - PPS Unit 4 PPT (1).ppt
PHP Barcelona 2010 - Architecture and testability
Vendredi Tech_ la programmation fonctionnelle.pptx
Fpga 13-task-and-functions
Software Engineering Best Practices @ Nylas
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
Getting Started with Test-Driven Development at Longhorn PHP 2023
Android design patterns
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...

More from ☁️ Mikhail Shilkov (8)

PDF
Monads Explained for OOP Developers
PDF
Performance Tales of Serverless - CloudNative London 2018
PPTX
Performance Tales of Serverless
PPTX
Monads Explained for OOP Developers
PPTX
Azure F#unctions
PDF
Azure F#unctions
PPTX
Event Driven Applications in F#
PDF
Why Learn F# and Functional Programming
Monads Explained for OOP Developers
Performance Tales of Serverless - CloudNative London 2018
Performance Tales of Serverless
Monads Explained for OOP Developers
Azure F#unctions
Azure F#unctions
Event Driven Applications in F#
Why Learn F# and Functional Programming

Recently uploaded (20)

PDF
Softaken Excel to vCard Converter Software.pdf
PPT
Introduction Database Management System for Course Database
PPTX
Transform Your Business with a Software ERP System
PDF
5 Lead Qualification Frameworks Every Sales Team Should Use
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
DOCX
The Five Best AI Cover Tools in 2025.docx
PPTX
Presentation of Computer CLASS 2 .pptx
PPT
JAVA ppt tutorial basics to learn java programming
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Introduction to Artificial Intelligence
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
ISO 45001 Occupational Health and Safety Management System
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
Mini project ppt template for panimalar Engineering college
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
Materi_Pemrograman_Komputer-Looping.pptx
PPTX
FLIGHT TICKET RESERVATION SYSTEM | FLIGHT BOOKING ENGINE API
PDF
top salesforce developer skills in 2025.pdf
Softaken Excel to vCard Converter Software.pdf
Introduction Database Management System for Course Database
Transform Your Business with a Software ERP System
5 Lead Qualification Frameworks Every Sales Team Should Use
2025 Textile ERP Trends: SAP, Odoo & Oracle
The Five Best AI Cover Tools in 2025.docx
Presentation of Computer CLASS 2 .pptx
JAVA ppt tutorial basics to learn java programming
PTS Company Brochure 2025 (1).pdf.......
Introduction to Artificial Intelligence
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Understanding Forklifts - TECH EHS Solution
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
ISO 45001 Occupational Health and Safety Management System
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Mini project ppt template for panimalar Engineering college
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Materi_Pemrograman_Komputer-Looping.pptx
FLIGHT TICKET RESERVATION SYSTEM | FLIGHT BOOKING ENGINE API
top salesforce developer skills in 2025.pdf

Introduction of Functional Programming