SlideShare ist ein Scribd-Unternehmen logo
1 von 53
OOP makes code understandable by encapsulating 
moving parts. FP makes code understandable by 
eliminating moving parts. 
Riccardo Terrell – Silicon Valley Code Camp 
2014 
— Michael Feathers 
(author of Working with Legacy 
Code)
Agenda 
History and influence of Functional Programming 
Functional vs Imperative Programming 
What is Functional Programming 
Functional Programming characteristics 
Why Functional Programming
History 
LISP 
ISWIM 
APL 
ML 
1973 
FP 
1958 1966 
1962 
1977 
2005F# Clojure 
1988Haskell 
Scala 2003 
2007 
Ocam 
1996 
l 
1930 
-ish 
1986Erlang 
Îť
Functional Programming 
Influence 
 Continue Evolution of GC – Lisp ~1958 
 Generics – ML ~ 1973 
 In early 1994, support for lambda, filter, map, and reduce was added to 
Python 
 List comprehension - Linq in C# 3.0 and Java 8 
 First-class functions were also introduce Visual Basic 9, C# and C++ 11 
 Java 8 supports lambda expressions as a replacement for anonymous 
classes 
 Is Lazy Evaluation is part of the main stream languages such as C# 
 Type Inference, example is the “var” keyword in C# 
Programming in a functional style can also be accomplished in languages that aren't
Objectives 
 Use functions as building block and composition to solve 
complex problem with simple code 
 Immutability and Isolation are your best friends to write 
concurrent application 
 Concurrency and reliability are becoming more and more required, 
FP will help you! 
 Functional and imperative styles should NOT stand in opposition 
… 
… they should COEXIST 
 Poly-paradigm programming is more powerful and effective 
than polyglot programming
FP vs OOP the Paradigm- 
Switch 
Functional Programming may look 
scary for an object-oriented 
developer because of all the strange 
buzzwords like Functor, Referential 
Transparency, Monads, etc., but they 
are really just unfamiliar terms. 
Object-oriented programming can be 
a scary one with all its concepts, e.g. 
polymorphism, encapsulation, 
inheritance, covariance, etc. 
?@#?%!
FP OOP Key Concepts 
 Functional Programming is different in many ways from a 
standard imperative language, but there are a few major 
differences that are particularly important to understand: 
Function-oriented 
not 
object-oriented 
Expressions 
rather than 
Statements 
Immutable 
rather than 
mutable
What is "Functional 
Programming?" 
Functional programming is just a style, is a programming paradigm 
that treats computation as the evaluation of functions and avoids 
state and mutable data… 
 “Functions as primary building blocks” (first-class functions) 
 programming with “immutable” variables and assignments, no state 
 Programs work by returning values instead of modifying data
What is "Functional 
Programming?" 
Functional programming is so called because a program consists entirely of 
functions. 
First class 
Higher-Order 
Functions 
Immutability 
Declarative 
Îť 
… is all about functions! Identifying an abstraction and building a function, 
use existing functions to build more complex abstractions, pass existing 
functions to other functions to build even more complex abstractions
Functional characteristics 
Higher Order Function & Pure Function 
Immutability 
Composition 
Curry & Partial Application
Higher-Order functions 
A higher-order function is a function that takes another function as a 
parameter, or a function that returns another function as a value, or a 
function which does both.
Pure Functions - Properties and 
Benefits 
 A function always gives the same output value for a given 
input value 
 I can then cache the result 
 A Pure Function has no side effects 
 Pure functions can be executed in parallel 
 The function does not rely on any external state 
 Increased readability and maintainability 
 Pure functions can more easily isolated 
 easier testing and debugging
Pure Functions - Properties and 
Benefits
Pure Functions - Properties and 
Benefits
Pure Functions - Properties and 
Benefits
Side Effects 
Side effects aren’t bad…
Unwanted Side Effects are Evil! 
Side effects aren’t bad… 
unwanted side effects are EVIL 
and the root of many bugs! 
One of the biggest advantages with functional 
programming is that the order of execution of “side 
effect free functions” is not important. 
… “side effect free functions” are 
easy to parallelize
Currying 
Curry is a technique in which a function is applied to its 
arguments one at a time, with each 
application returning a new function 
that accepts the next argument 
Higher-order function enable 
Partial Application and Currying
Partial Application 
Partial Application refers to the process of fixing a 
number of arguments to a function, producing 
another function of smaller arity 
With both currying and partial application, you supply argument values and return a 
function that’s invokable with the missing arguments. But currying a function returns 
the next function in the chain, whereas partial application binds argument values to 
values that you supply during the operation, producing a function with a smaller arity
Immutability 
 Immutability is very important characteristic of FP but mostly is about transformation of 
state… … Immutable data forces you to use a “transformational” approach 
 When you’re writing programs using 
immutable types, the only “thing a method 
can do is return a result, it can’t modify the 
state of any objects 
 Immutable data makes the code predictable 
is easier to work 
 Prevent Bugs 
 Concurrency is much simpler, as you don’t 
have to worry about using locks to avoid 
update conflicts 
 Automatic thread-safe, controlling mutable state in
Immutability 
Mutable values cannot be captured by 
closures!
Function Composition 
Function Composition - Building with composition. Composition is the 
'glue' that allows us build larger systems from smaller ones. This is the very 
heart of the functional style. Almost every line of code is a composable 
expression. Composition is used to build basic functions, and then functions 
that use those functions, and so on. 
Composition — in the form of passed parameters plus first-class functions
Using functions as building 
blocks 
 A well-known principle of good design is to create a set of basic 
operations and then combine these building blocks in various 
ways to build up more complex behaviors
Compose Mario 
Mario game sample, based on functional reactive Elm script (http://elm-lang. 
org/edit/examples/Intermediate/Mario.elm) 
The functions that depend on keyboard take the current keyboard state as the first argument. This is 
represented as a tuple int*int (dir) consisting of x and y directions. 
The step function of the game takes previous Mario value and returns a new one. It is composed from 4 
functions that represent different aspects of the game.
Memoization 
Memoization enables automatic caching of recurring 
function-return values.
Lazy Evaluation - Strict & Non-Strict 
Evaluation 
 Lazy evaluation deferral of expression evaluation for as long 
as possible until absolutely needed 
 Languages can be categorized as strict (eagerly evaluating 
all expressions) or lazy (deferring evaluation) 
 Strict evaluation always fully evaluates 
function arguments before invoking the 
function 
 Lazy evaluation does not evaluate function 
arguments unless their values are required to 
evaluate the function call itself
Recursion is the new iteration 
 In functional programming “iteration” is ~usually~ accomplished via 
recursion 
 Recursive function invoke themselves, Tail recursion is optimized by 
compiler avoiding to maintain a stack ~stack over flow!
Recursion is the new iteration 
 In functional programming “iteration” is ~usually~ accomplished via 
recursion
Recursion
Tail Recursion
Why Functional Programming?
Why Functional Programming? 
 Changes the way you think about programming and problem 
solving 
 Functional Programming promotes Composition and Modularity 
 Simple Code for Complex Problems 
 Declarative programming style 
 Concurrency, FP is easy to parallelize 
 Locking vs. immutable memory 
 Conciseness, less code (no null checking) 
 Correctness & Reduced bugs (immutability) 
 Rapid Prototyping
Concurrency 
Modern computers come with 
multiple processors, each 
equipped with multiple cores, but 
the single processor is slower 
than used to be! Moore’s law 
(http://en.wikipedia.org/wiki/Moore's_law) 
… to achieve great performances the 
application must be leveraging a 
Concurrent Model
Concurrency 
There is a problem… 
the free lunch is over 
 Programs are not doubling in speed every 
couple of years for free anymore 
We need to start writing code to take 
advantage of many cores
Concurrency… jams to avoid! 
Parallel, asynchronous, 
concurrent, and reactive 
programs bring many 
challenges because these 
programs are nearly always 
nondeterministic 
 This makes debugging/testing 
challenging 
 Deadlocking 
 Not easy to program
Concurrency 
 Imperative and traditional 
programming styles gives 
us bad headaches 
 It’s difficult to turn existing sequential 
code into parallel code 
 Using shared state and locks is 
difficult 
 different threads can change the same
Concurrency 
 Functional programming feels 
good: 
 Thanks to the immutability (and isolation), 
we avoid introducing race conditions and we 
can write lock-free code. 
 Using a declarative programming style 
we can introduce parallelism into 
existing code easily. We can replace a 
few primitives that specify how to 
combine commands with version that 
executes commands in parallel
Concurrent Model Programming 
An Agent is an independent computational 
entity which contains a queue, and receives 
IMMUTABILITY + 
ISOLATION + 
and processes messages 
DECLARATIVE PROGRAMMING = 
------------------------------------------------ 
It provides immutability and isolation 
BEST CONCURRENT MODEL 
PROGRAMMING 
(it enforces coarse-grained isolation through message-passing)
What does an Agent look like?
Agent Model 
What does a 
system of 
actors look 
like?
Pipeline Processing 
 Pipeline according to Wikipedia: 
 A pipeline is a set of data processing elements 
connected in series, so that the output of one element 
is the input of the next one. The elements of a pipeline 
are often executed in parallel or in time-sliced fashion; 
in that case, some amount of buffer storage is often 
inserted between elements
Agent Async-BoundedQueue
Agent Async-BoundedQueue
Pipeline Processing 
 Values processed in multiple steps 
 Worker takes value, processes 
it, and sends it 
 Worker is blocked when source 
is empty 
 Worker is blocked when target 
is full 
 Steps of the pipeline run in 
parallel
When Functional 
Programming?
Functional Job Trend 
Functional languages are 
sprouting not just on the 
JVM where the two most 
interesting new languages 
are Scala and Clojure, but 
also on the .NET platform, 
where F# is a first-class 
citizen 
http://www.itjobswatch.co.uk
Wrap-Up 
 Use functions as building block and composition to solve complex 
problem with simple code 
 Immutability and Isolation are your best friends to write concurrent 
application 
 Concurrency and reliability are becoming more and more required, FP will help you! 
 Functional and imperative styles should NOT stand in opposition 
but… 
…they should COEXIST 
 Poly-paradigm programming is more powerful 
and effective than polyglot programming
Q & A ? 
The tools we use have a profound (and devious!) influence on our 
thinking habits, and, therefore, on our thinking abilities. 
-- Edsger Dijkstra
References 
 Why Functional Programming Matters (John Hughes) 
http://www.cs.kent.ac.uk/people/staff/dat/miranda/whyfp90.pdf 
 http://rosettacode.org
How to reach me 
github.com/DCFsharp 
meetup.com/DC-fsharp/ 
@DCFsharp 
rterrell@microsoft.com

Weitere ähnliche Inhalte

Was ist angesagt?

C++ OOP Implementation
C++ OOP ImplementationC++ OOP Implementation
C++ OOP Implementation
Fridz Felisco
 
Integrated Language Definition Testing: Enabling Test-Driven Language Develop...
Integrated Language Definition Testing: Enabling Test-Driven Language Develop...Integrated Language Definition Testing: Enabling Test-Driven Language Develop...
Integrated Language Definition Testing: Enabling Test-Driven Language Develop...
lennartkats
 

Was ist angesagt? (20)

C programming interview questions
C programming interview questionsC programming interview questions
C programming interview questions
 
C++ to java
C++ to javaC++ to java
C++ to java
 
FregeDay: Roadmap for resolving differences between Haskell and Frege (Ingo W...
FregeDay: Roadmap for resolving differences between Haskell and Frege (Ingo W...FregeDay: Roadmap for resolving differences between Haskell and Frege (Ingo W...
FregeDay: Roadmap for resolving differences between Haskell and Frege (Ingo W...
 
Functional JavaScript Fundamentals
Functional JavaScript FundamentalsFunctional JavaScript Fundamentals
Functional JavaScript Fundamentals
 
Programming In C++
Programming In C++ Programming In C++
Programming In C++
 
C++ OOP Implementation
C++ OOP ImplementationC++ OOP Implementation
C++ OOP Implementation
 
Pascal Programming Language
Pascal Programming LanguagePascal Programming Language
Pascal Programming Language
 
Functional Programming in Python
Functional Programming in PythonFunctional Programming in Python
Functional Programming in Python
 
Integrated Language Definition Testing: Enabling Test-Driven Language Develop...
Integrated Language Definition Testing: Enabling Test-Driven Language Develop...Integrated Language Definition Testing: Enabling Test-Driven Language Develop...
Integrated Language Definition Testing: Enabling Test-Driven Language Develop...
 
C++ question and answers
C++ question and answersC++ question and answers
C++ question and answers
 
C#
C#C#
C#
 
Immutable data structures - A Primer
Immutable data structures - A PrimerImmutable data structures - A Primer
Immutable data structures - A Primer
 
Programming Paradigm & Languages
Programming Paradigm & LanguagesProgramming Paradigm & Languages
Programming Paradigm & Languages
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++
 
Basic structure of C++ program
Basic structure of C++ programBasic structure of C++ program
Basic structure of C++ program
 
C++vs java
C++vs javaC++vs java
C++vs java
 
Introduction to F# 3.0
Introduction to F# 3.0Introduction to F# 3.0
Introduction to F# 3.0
 
Python Programming - I. Introduction
Python Programming - I. IntroductionPython Programming - I. Introduction
Python Programming - I. Introduction
 
Preparing for Scala 3
Preparing for Scala 3Preparing for Scala 3
Preparing for Scala 3
 

Andere mochten auch

Lesson Four - Seerah
Lesson Four - SeerahLesson Four - Seerah
Lesson Four - Seerah
Ebrahim Ismail
 
Crime thriller, md, jd, jh hg
Crime thriller, md, jd, jh hgCrime thriller, md, jd, jh hg
Crime thriller, md, jd, jh hg
hayleigh282
 
Tolan revfinal conf_2013
Tolan revfinal conf_2013Tolan revfinal conf_2013
Tolan revfinal conf_2013
youth_nex
 
Lesson five miracles
Lesson five   miraclesLesson five   miracles
Lesson five miracles
Ebrahim Ismail
 
Tahneek lesson 7
Tahneek   lesson 7Tahneek   lesson 7
Tahneek lesson 7
Ebrahim Ismail
 
Just cavalli presentation
Just cavalli presentationJust cavalli presentation
Just cavalli presentation
alexxturrell
 
ConnectME: connecting content for future TV & video
ConnectME: connecting content for future TV & videoConnectME: connecting content for future TV & video
ConnectME: connecting content for future TV & video
connectme_project
 

Andere mochten auch (20)

Functional Programming in C# and F#
Functional Programming in C# and F#Functional Programming in C# and F#
Functional Programming in C# and F#
 
Presentaciones digitales. MPM
Presentaciones digitales. MPMPresentaciones digitales. MPM
Presentaciones digitales. MPM
 
Learning the city powerpointfrom am v3
Learning the city powerpointfrom am v3Learning the city powerpointfrom am v3
Learning the city powerpointfrom am v3
 
Lesson Four - Seerah
Lesson Four - SeerahLesson Four - Seerah
Lesson Four - Seerah
 
The New European PV Legislation: Issues and Challenges
The New European PV Legislation: Issues and ChallengesThe New European PV Legislation: Issues and Challenges
The New European PV Legislation: Issues and Challenges
 
Crime thriller, md, jd, jh hg
Crime thriller, md, jd, jh hgCrime thriller, md, jd, jh hg
Crime thriller, md, jd, jh hg
 
Maps
MapsMaps
Maps
 
toxic molds
toxic molds toxic molds
toxic molds
 
Tolan revfinal conf_2013
Tolan revfinal conf_2013Tolan revfinal conf_2013
Tolan revfinal conf_2013
 
عروض موقع سوق مصر
عروض موقع سوق مصرعروض موقع سوق مصر
عروض موقع سوق مصر
 
Lesson 21 - Building up to Prophethood
Lesson 21 - Building up to ProphethoodLesson 21 - Building up to Prophethood
Lesson 21 - Building up to Prophethood
 
Lesson five miracles
Lesson five   miraclesLesson five   miracles
Lesson five miracles
 
Tahneek lesson 7
Tahneek   lesson 7Tahneek   lesson 7
Tahneek lesson 7
 
Just cavalli presentation
Just cavalli presentationJust cavalli presentation
Just cavalli presentation
 
ConnectME: connecting content for future TV & video
ConnectME: connecting content for future TV & videoConnectME: connecting content for future TV & video
ConnectME: connecting content for future TV & video
 
Trecho de "O livro das religiĂľes"
Trecho de "O livro das religiĂľes"Trecho de "O livro das religiĂľes"
Trecho de "O livro das religiĂľes"
 
Empirical Experiment on Navigation with Social Tags
Empirical Experiment on Navigation with Social TagsEmpirical Experiment on Navigation with Social Tags
Empirical Experiment on Navigation with Social Tags
 
Bringithomefurniture pdf
Bringithomefurniture pdfBringithomefurniture pdf
Bringithomefurniture pdf
 
Connected Media Experiences
Connected Media ExperiencesConnected Media Experiences
Connected Media Experiences
 
Lesson 13 Death of Amina, In the care of Abdul Muttalib and Abu Talib.
Lesson 13   Death of Amina, In the care of Abdul Muttalib and Abu Talib.Lesson 13   Death of Amina, In the care of Abdul Muttalib and Abu Talib.
Lesson 13 Death of Amina, In the care of Abdul Muttalib and Abu Talib.
 

Ähnlich wie Why functional programming in C# & F#

Functional Paradigm.pptx
Functional Paradigm.pptxFunctional Paradigm.pptx
Functional Paradigm.pptx
FurretMaster
 

Ähnlich wie Why functional programming in C# & F# (20)

Functional programming in TypeScript
Functional programming in TypeScriptFunctional programming in TypeScript
Functional programming in TypeScript
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
 
Unit 1
Unit 1Unit 1
Unit 1
 
JAVA
JAVAJAVA
JAVA
 
Java 3 rd sem. 2012 aug.ASSIGNMENT
Java 3 rd sem. 2012 aug.ASSIGNMENTJava 3 rd sem. 2012 aug.ASSIGNMENT
Java 3 rd sem. 2012 aug.ASSIGNMENT
 
Designing function families and bundles with java's behaviors parameterisatio...
Designing function families and bundles with java's behaviors parameterisatio...Designing function families and bundles with java's behaviors parameterisatio...
Designing function families and bundles with java's behaviors parameterisatio...
 
Functional programming is the most extreme programming
Functional programming is the most extreme programmingFunctional programming is the most extreme programming
Functional programming is the most extreme programming
 
Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)
 
PCCF UNIT 2 CLASS.pptx
PCCF UNIT 2 CLASS.pptxPCCF UNIT 2 CLASS.pptx
PCCF UNIT 2 CLASS.pptx
 
Object Oriented programming - Introduction
Object Oriented programming - IntroductionObject Oriented programming - Introduction
Object Oriented programming - Introduction
 
Oop.pptx
Oop.pptxOop.pptx
Oop.pptx
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
 
Functional Browser Automation Testing for Newbs
Functional Browser Automation Testing for NewbsFunctional Browser Automation Testing for Newbs
Functional Browser Automation Testing for Newbs
 
Mastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_argumentsMastering Python lesson 4_functions_parameters_arguments
Mastering Python lesson 4_functions_parameters_arguments
 
The Design, Evolution and Use of KernelF
The Design, Evolution and Use of KernelFThe Design, Evolution and Use of KernelF
The Design, Evolution and Use of KernelF
 
Python functional programming
Python functional programmingPython functional programming
Python functional programming
 
Presentation1.pptx
Presentation1.pptxPresentation1.pptx
Presentation1.pptx
 
Functional Paradigm.pptx
Functional Paradigm.pptxFunctional Paradigm.pptx
Functional Paradigm.pptx
 

KĂźrzlich hochgeladen

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
Christopher Logan Kennedy
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

KĂźrzlich hochgeladen (20)

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Why functional programming in C# & F#

  • 1. OOP makes code understandable by encapsulating moving parts. FP makes code understandable by eliminating moving parts. Riccardo Terrell – Silicon Valley Code Camp 2014 — Michael Feathers (author of Working with Legacy Code)
  • 2. Agenda History and influence of Functional Programming Functional vs Imperative Programming What is Functional Programming Functional Programming characteristics Why Functional Programming
  • 3. History LISP ISWIM APL ML 1973 FP 1958 1966 1962 1977 2005F# Clojure 1988Haskell Scala 2003 2007 Ocam 1996 l 1930 -ish 1986Erlang Îť
  • 4. Functional Programming Influence  Continue Evolution of GC – Lisp ~1958  Generics – ML ~ 1973  In early 1994, support for lambda, filter, map, and reduce was added to Python  List comprehension - Linq in C# 3.0 and Java 8  First-class functions were also introduce Visual Basic 9, C# and C++ 11  Java 8 supports lambda expressions as a replacement for anonymous classes  Is Lazy Evaluation is part of the main stream languages such as C#  Type Inference, example is the “var” keyword in C# Programming in a functional style can also be accomplished in languages that aren't
  • 5. Objectives  Use functions as building block and composition to solve complex problem with simple code  Immutability and Isolation are your best friends to write concurrent application  Concurrency and reliability are becoming more and more required, FP will help you!  Functional and imperative styles should NOT stand in opposition … … they should COEXIST  Poly-paradigm programming is more powerful and effective than polyglot programming
  • 6. FP vs OOP the Paradigm- Switch Functional Programming may look scary for an object-oriented developer because of all the strange buzzwords like Functor, Referential Transparency, Monads, etc., but they are really just unfamiliar terms. Object-oriented programming can be a scary one with all its concepts, e.g. polymorphism, encapsulation, inheritance, covariance, etc. ?@#?%!
  • 7. FP OOP Key Concepts  Functional Programming is different in many ways from a standard imperative language, but there are a few major differences that are particularly important to understand: Function-oriented not object-oriented Expressions rather than Statements Immutable rather than mutable
  • 8. What is "Functional Programming?" Functional programming is just a style, is a programming paradigm that treats computation as the evaluation of functions and avoids state and mutable data…  “Functions as primary building blocks” (first-class functions)  programming with “immutable” variables and assignments, no state  Programs work by returning values instead of modifying data
  • 9. What is "Functional Programming?" Functional programming is so called because a program consists entirely of functions. First class Higher-Order Functions Immutability Declarative Îť … is all about functions! Identifying an abstraction and building a function, use existing functions to build more complex abstractions, pass existing functions to other functions to build even more complex abstractions
  • 10. Functional characteristics Higher Order Function & Pure Function Immutability Composition Curry & Partial Application
  • 11. Higher-Order functions A higher-order function is a function that takes another function as a parameter, or a function that returns another function as a value, or a function which does both.
  • 12. Pure Functions - Properties and Benefits  A function always gives the same output value for a given input value  I can then cache the result  A Pure Function has no side effects  Pure functions can be executed in parallel  The function does not rely on any external state  Increased readability and maintainability  Pure functions can more easily isolated  easier testing and debugging
  • 13. Pure Functions - Properties and Benefits
  • 14. Pure Functions - Properties and Benefits
  • 15. Pure Functions - Properties and Benefits
  • 16. Side Effects Side effects aren’t bad…
  • 17. Unwanted Side Effects are Evil! Side effects aren’t bad… unwanted side effects are EVIL and the root of many bugs! One of the biggest advantages with functional programming is that the order of execution of “side effect free functions” is not important. … “side effect free functions” are easy to parallelize
  • 18. Currying Curry is a technique in which a function is applied to its arguments one at a time, with each application returning a new function that accepts the next argument Higher-order function enable Partial Application and Currying
  • 19. Partial Application Partial Application refers to the process of fixing a number of arguments to a function, producing another function of smaller arity With both currying and partial application, you supply argument values and return a function that’s invokable with the missing arguments. But currying a function returns the next function in the chain, whereas partial application binds argument values to values that you supply during the operation, producing a function with a smaller arity
  • 20. Immutability  Immutability is very important characteristic of FP but mostly is about transformation of state… … Immutable data forces you to use a “transformational” approach  When you’re writing programs using immutable types, the only “thing a method can do is return a result, it can’t modify the state of any objects  Immutable data makes the code predictable is easier to work  Prevent Bugs  Concurrency is much simpler, as you don’t have to worry about using locks to avoid update conflicts  Automatic thread-safe, controlling mutable state in
  • 21. Immutability Mutable values cannot be captured by closures!
  • 22. Function Composition Function Composition - Building with composition. Composition is the 'glue' that allows us build larger systems from smaller ones. This is the very heart of the functional style. Almost every line of code is a composable expression. Composition is used to build basic functions, and then functions that use those functions, and so on. Composition — in the form of passed parameters plus first-class functions
  • 23. Using functions as building blocks  A well-known principle of good design is to create a set of basic operations and then combine these building blocks in various ways to build up more complex behaviors
  • 24. Compose Mario Mario game sample, based on functional reactive Elm script (http://elm-lang. org/edit/examples/Intermediate/Mario.elm) The functions that depend on keyboard take the current keyboard state as the first argument. This is represented as a tuple int*int (dir) consisting of x and y directions. The step function of the game takes previous Mario value and returns a new one. It is composed from 4 functions that represent different aspects of the game.
  • 25.
  • 26. Memoization Memoization enables automatic caching of recurring function-return values.
  • 27. Lazy Evaluation - Strict & Non-Strict Evaluation  Lazy evaluation deferral of expression evaluation for as long as possible until absolutely needed  Languages can be categorized as strict (eagerly evaluating all expressions) or lazy (deferring evaluation)  Strict evaluation always fully evaluates function arguments before invoking the function  Lazy evaluation does not evaluate function arguments unless their values are required to evaluate the function call itself
  • 28. Recursion is the new iteration  In functional programming “iteration” is ~usually~ accomplished via recursion  Recursive function invoke themselves, Tail recursion is optimized by compiler avoiding to maintain a stack ~stack over flow!
  • 29. Recursion is the new iteration  In functional programming “iteration” is ~usually~ accomplished via recursion
  • 32.
  • 34. Why Functional Programming?  Changes the way you think about programming and problem solving  Functional Programming promotes Composition and Modularity  Simple Code for Complex Problems  Declarative programming style  Concurrency, FP is easy to parallelize  Locking vs. immutable memory  Conciseness, less code (no null checking)  Correctness & Reduced bugs (immutability)  Rapid Prototyping
  • 35. Concurrency Modern computers come with multiple processors, each equipped with multiple cores, but the single processor is slower than used to be! Moore’s law (http://en.wikipedia.org/wiki/Moore's_law) … to achieve great performances the application must be leveraging a Concurrent Model
  • 36. Concurrency There is a problem… the free lunch is over  Programs are not doubling in speed every couple of years for free anymore We need to start writing code to take advantage of many cores
  • 37. Concurrency… jams to avoid! Parallel, asynchronous, concurrent, and reactive programs bring many challenges because these programs are nearly always nondeterministic  This makes debugging/testing challenging  Deadlocking  Not easy to program
  • 38. Concurrency  Imperative and traditional programming styles gives us bad headaches  It’s difficult to turn existing sequential code into parallel code  Using shared state and locks is difficult  different threads can change the same
  • 39. Concurrency  Functional programming feels good:  Thanks to the immutability (and isolation), we avoid introducing race conditions and we can write lock-free code.  Using a declarative programming style we can introduce parallelism into existing code easily. We can replace a few primitives that specify how to combine commands with version that executes commands in parallel
  • 40. Concurrent Model Programming An Agent is an independent computational entity which contains a queue, and receives IMMUTABILITY + ISOLATION + and processes messages DECLARATIVE PROGRAMMING = ------------------------------------------------ It provides immutability and isolation BEST CONCURRENT MODEL PROGRAMMING (it enforces coarse-grained isolation through message-passing)
  • 41. What does an Agent look like?
  • 42. Agent Model What does a system of actors look like?
  • 43. Pipeline Processing  Pipeline according to Wikipedia:  A pipeline is a set of data processing elements connected in series, so that the output of one element is the input of the next one. The elements of a pipeline are often executed in parallel or in time-sliced fashion; in that case, some amount of buffer storage is often inserted between elements
  • 46. Pipeline Processing  Values processed in multiple steps  Worker takes value, processes it, and sends it  Worker is blocked when source is empty  Worker is blocked when target is full  Steps of the pipeline run in parallel
  • 47.
  • 49. Functional Job Trend Functional languages are sprouting not just on the JVM where the two most interesting new languages are Scala and Clojure, but also on the .NET platform, where F# is a first-class citizen http://www.itjobswatch.co.uk
  • 50. Wrap-Up  Use functions as building block and composition to solve complex problem with simple code  Immutability and Isolation are your best friends to write concurrent application  Concurrency and reliability are becoming more and more required, FP will help you!  Functional and imperative styles should NOT stand in opposition but… …they should COEXIST  Poly-paradigm programming is more powerful and effective than polyglot programming
  • 51. Q & A ? The tools we use have a profound (and devious!) influence on our thinking habits, and, therefore, on our thinking abilities. -- Edsger Dijkstra
  • 52. References  Why Functional Programming Matters (John Hughes) http://www.cs.kent.ac.uk/people/staff/dat/miranda/whyfp90.pdf  http://rosettacode.org
  • 53. How to reach me github.com/DCFsharp meetup.com/DC-fsharp/ @DCFsharp rterrell@microsoft.com

Hinweis der Redaktion

  1. Recursion to do not modify the list
  2. Many people find functional programming elegant or even beautiful, but that’s hardly a good reason to use it in a commercial environment. Elegance doesn’t pay the bills, sad to say. One of the big reason for coding in a functional style is that it makes you and your team more productive.