SlideShare a Scribd company logo
Functional Programming FundamentalsElements of Functional Programmingl1Shahriar HyderMarch 30, 2010Kaz Software Ltd.
”Life is too short for imperative programming”John Hughes2Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Productivity“It’s really clear that the imperative style of programming has run its course. ... We’re sort of done with that. … However, in the declarative realm we can speculate a 10x improvement in productivity in certain domains.”Anders Hejlsberg  C# Architect(from his MIX07 keynote)3Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Origins4Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Originsfunctional programming emerged slightly by accident from several sourcessymbolic logic, specifically the l-calculus (A.Church 1930s) and combinatory logic (H.Curry 1930s)	λop.λx.(op x x)	(λop.λx.(op x x)) (+) 21 = (λx.((+) x x)) 21 = (+) 21 21 = 42the symbolic manipulation strand of Artificial Intelligence, or rather: LISP (J.McCarthy 1960)pseudo-code for CS publications, ISWIM (P.Landin 1966)support languages for logic and mathematics, e.g. LCF’s metalanguageML (Milner et. al. 1970s)OCaml – 1996F# (and parts of C#) – 20025Shahriar HyderMarch 30, 2010Kaz Software Ltd.
λ-calculus Building BlockAnonymous functions SupportJavaScriptPHP 4.0.1 – PHP 5.2.x (kinda)PHP 5.3 (more kinda)C# 2.0Java – Hardly any support. Anonymous Classes to use Closures. Java also supports another form of classes, which are called inner (or nested) classes. These are defined in the body of an enclosing class and have full access to each and every instance variable of the enclosing class, thus resembling standard function closures. 6Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Fundamentals of FP LanguagesThe objective of the design of a FPL is to mimic mathematical functions to the greatest extent possibleThe basic process of computation is fundamentally different in a FPL than in an imperative languageIn an imperative language, operations are done and the results are stored in variables for later useManagement of variables is a constant concern and source of complexity for imperative programmingIn an FPL, variables are not necessary, as is the case in mathematics7Shahriar HyderMarch 30, 2010Kaz Software Ltd.
What is object-oriented programming?Object-oriented programming is a style of	programming that enables you:	- Reuse code (via classes)	- Eliminate bugs (via encapsulating, data hiding)8Shahriar HyderMarch 30, 2010Kaz Software Ltd.
What is functional programming?Functional programming is a style of programming	that enables you:	- Re-use code (via function composition)	- Eliminate bugs (via immutability)9Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Moore’s Law Ran Out!10Shahriar HyderMarch 30, 2010Kaz Software Ltd.
“Software gets slower faster than hardware gets faster”							--Wirth’s Law11Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Von Neumann syndromeFor most applications in massively parallel computing systems with thousands or tens of thousands of processors the performance can be less than hoped. Sometimes called a "supercomputing crisis" it is believed to be due to two factors. Firstly a hardware barrier in the efficiency in moving data, called the memory wall or von Neumann bottleneck (An inefficiency inherent in the design of any von Neumann machine [The von Neumann architecture is a design model for a stored-program digital computer that uses a central processing unit (CPU) and a single separate storage structure ("memory") to hold both instructions and data. It has a sequential architecture.]that arises from the fact that most computer time is spent in moving information between storage and the central processing unit rather than operating on it. ). Secondly a fall in programmer productivity when faced with systems that are massively parallel, the difficulties in developing for parallelism (or thread-level parallelism in multi-core CPUs) when previously this was not an issue.12Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Wikipedia!In computer science, functional programming is a programming paradigm that treats computation  as the evaluation of mathematical functions and avoids state  and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state.  Functional programming has its roots in the lambda calculus, a formal system developed in the 1930s to investigate function definition, function application, and recursion. Many functional programming languages can be viewed as elaborations on the lambda calculus.In practice, the difference between a mathematical function and the notion of a "function" used in imperative programming is that imperative functions can have side effects, changing the value of already calculated computations. Because of this they lack referential transparency, i.e. the same language expression can result in different values at different times depending on the state of the executing program. Conversely, in functional code, the output value of a function depends only on the arguments that are input to the function, so calling a function f twice with the same value for an argument x will produce the same result f(x) both times. Eliminating side-effects can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development of functional programming.13
14Shahriar HyderMarch 30, 2010Kaz Software Ltd.
15Shahriar HyderMarch 30, 2010Kaz Software Ltd.
16Shahriar HyderMarch 30, 2010Kaz Software Ltd.
17Shahriar HyderMarch 30, 2010Kaz Software Ltd.
18Shahriar HyderMarch 30, 2010Kaz Software Ltd.
19Shahriar HyderMarch 30, 2010Kaz Software Ltd.
20Shahriar HyderMarch 30, 2010Kaz Software Ltd.
21Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Functional LanguagesHaskellCleanF#ML / OCamlLisp / SchemeScala
Clojure
XSLT
Erlang
SQL
Mathematica22Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Pure Functional LanguagesHaskellCleanF#ML / OCamlLisp / SchemeScala
Clojure
XSLT
Erlang
SQL
MathematicaPurely functional is a term in computing used to describe algorithms, data structures or programming languages that exclude destructive modifications (updates). According to this restriction, variables are used in a mathematical sense, with identifiers referring to immutable, persistent values.23Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Is it too hard?24Shahriar HyderMarch 30, 2010Kaz Software Ltd.
The foundation25Shahriar HyderMarch 30, 2010Kaz Software Ltd.
What is a function?y = f(x)26Shahriar HyderMarch 30, 2010Kaz Software Ltd.
FP Preachings!Avoid Side-Effects!Do not modify variables passed to themDo not modify any global variable27Shahriar HyderMarch 30, 2010Kaz Software Ltd.
FP Preachings!Avoid Mutation!“Mutation Considered Harmful” 28Shahriar HyderMarch 30, 2010Kaz Software Ltd.
FP Preachings!Variables only assigned onceSame input -> Same outputFunctions return valuesGiven a set of values in the parameter list, the function can only have one possible result.No Shared State29Shahriar HyderMarch 30, 2010Kaz Software Ltd.
FP Preachings!Does order matter?Order is a side effect as well..30Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Functional ProgrammingFocus on results not processEmphasis is on what is to be computed not how it HappensData is immutableFunctions are data tooDecompose problem into ‘functions’31Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Data is immutablex = x + 1;Why should a function in C never return a pointer?Why should you make a copy of an internal array before returning it from your class?Why is multi-threading so damn hard?32Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Why bother?Pure functions can be executed in parallel without interfering with one anotherPure functions can be “perfectly” cachedPure functions can be “partially” appliedFunctions can receive and return functions, for which all of the above hold trueAllows for greater “modularity” and “composability”33Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Code!//F#openSystemlet a = 2Console.WriteLine a//C#using System;namespace ConsoleApplication1{classProgram{staticint a(){return 2;}static void Main(string[] args){Console.WriteLine(a);            }}}34Shahriar HyderMarch 30, 2010Kaz Software Ltd.
More Code!//F#openSystemlet a = 2Console.WriteLine a//C#using System;namespace ConsoleApplication1{classProgram{static nta(){return2;}static void Main(string[] args){Console.WriteLine(a);            }}}More Noise Than Signal!35Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Refactoring “hole in the middle”Header() { ■ ■ ■ }Footer() { ■ ■ ■ }Red() { ■ ■■ }Blue() { ■ ■■ }Foo(){    Header();Red();    Footer();}Bar(){    Header();Blue();    Footer();}Factor out the differences and the similarities?!36Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Refactoring “hole in the middle”Red() { ■ ■■ }Blue() { ■ ■■ }FooBar(func){■ ■ ■func();■ ■ ■}The “FP Way” is to simply pass in an implementation of the “hole” to be filled:FooBar( {■ ■■});37Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Example: Sorting by multiple keysclassGasResult{publicGasResult(…)  { … }publicreadonlystring Name;publicreadonlydouble Price;publicreadonlydouble Distance;}Problem: You want to sort lists of GasResults by various keys.38Shahriar HyderMarch 30, 2010Kaz Software Ltd.
OO Approach: Many IComparersclassGasResult{    …publicclassGasPriceComparer : IComparer<GasResult>    {   publicint Compare(GasResult a, GasResult b)        {   returna.Price.CompareTo(b.Price);   }   }publicstaticGasPriceComparerGasPriceComparison =newGasPriceComparer();}Array.Sort<GasResult>(results, GasResult.GasPriceComparison);39Shahriar HyderMarch 30, 2010Kaz Software Ltd.
OO Approach: Many IComparersclassGasResult{    …publicclassGasNameComparer : IComparer<GasResult>    {   publicint Compare(GasResult a, GasResult b)        {   returna.Name.CompareTo(b.Name);   }   }publicstaticGasNameComparerGasNameComparison =newGasNameComparer();}Array.Sort<GasResult>(results, GasResult.GasNameComparison);40Shahriar HyderMarch 30, 2010Kaz Software Ltd.
OO Approach: Many IComparersclassGasResult{    …publicclassGasDistanceComparer : IComparer<GasResult>    {   publicint Compare(GasResult a, GasResult b)        {   returna.Distance.CompareTo(b.Distance);   }   }publicstaticGasDistanceComparerGasDistanceComparison =newGasDistanceComparer();}Array.Sort<GasResult>(results, GasResult.GasDistanceComparison);41Shahriar HyderMarch 30, 2010Kaz Software Ltd.
FP Approach: Passed in lambdasclassGasResult{    …}results.OrderBy<GasResult,double>(r => r.Price);results.OrderBy<GasResult,string>(r => r.Name);results.OrderBy<GasResult,double>(r => r.Distance);(extension) IOrderedSequence<TSource>IEnumerable<TSource>.OrderBy<TSource, TKey>(Func<TSource, Tkey> keySelector)42Shahriar HyderMarch 30, 2010Kaz Software Ltd.
43Shahriar HyderMarch 30, 2010Kaz Software Ltd.
First-class functionIn computer science, a programming language is said to support first-class functions if it treats functions as first-class objects. Specifically, this means that the language supports constructing new functions during the execution of a program, storing them in data structures, passing them as arguments to other functions, and returning them as the values of other functions.44Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Closure (computer science)In computer science, a closure is a first-class function with free variables that are bound in the lexical environment. Such a function is said to be "closed over" its free variables. A closure is defined within the scope of its free variables, and the extent of those variables is at least as long as the lifetime of the closure itself..45Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Closures46Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Closure exampleHere is an example rewritten in ECMAScript (JavaScript) :	// Return a list of all books with at least 'threshold' copies sold. function bestSellingBooks(threshold) { returnbookList.filter( function (book) {returnbook.sales >= threshold; 			} );	}A function may create a closure and return it, as in the following example:	// Return a function that approximates the derivative of f // using an interval of dx, which should be appropriately small. function derivative(f, dx) {	return function (x) {		return (f(x + dx) - f(x)) / dx; 	};}Because the closure in this case outlives the scope of the function that creates it, the variables f and dx live on after the function derivative returns. In languages without closures, the lifetime of a local variable coincides with the execution of the scope where that variable is declared. In languages with closures, variables must continue to exist as long as any existing closures have references to them. This is most commonly implemented using some form of garbage collection.47Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Generators/* Method that takes an iterable input (possibly an array) and returns all even numbers. */ publicstaticIEnumerable<int> GetEven(IEnumerable<int> numbers) { foreach (intiin numbers) { if ((i % 2) == 0) { yieldreturni; 		} 	} } You may even use multiple yield return statements and the compiler will return them in order on each iteration:publicclassCityCollection : IEnumerable<string> {publicIEnumerator<string> GetEnumerator() {	yieldreturn"New York"; 	yieldreturn"Paris"; 	yieldreturn"London"; } }48Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Higher order functions     Higher-order functions are closely related to first-class functions, in that higher-order functions and first-class functions both allow functions as arguments and results of other functions. The distinction between the two is subtle: "higher-order" describes a mathematical concept of functions that operate on other functions, while "first-class" is a computer science term that describes programming language entities that have no restriction on their use (thus first-class functions can appear anywhere in the program that other first-class entities like numbers can, including as arguments to other functions and as their return values).49Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Higher order function example//f is a function function derivative(f) { return function(x) { //approximation of derivative return (f(x + 0.00001) f(x)) / 0.00001;     	} } 50Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Higher order function example//evaluate derivative of x2: varderiv_x_squared = derivative(     function(x) {         return x*x;     } ); alert(deriv_x_squared(3)); //alerts 6ish51Shahriar HyderMarch 30, 2010Kaz Software Ltd.
52Shahriar HyderMarch 30, 2010Kaz Software Ltd.
53Shahriar HyderMarch 30, 2010Kaz Software Ltd.
54Shahriar HyderMarch 30, 2010Kaz Software Ltd.
55Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Map/Reduce/FilterdoubleCheapGasNearby(IEnumerable<GasResult> results) {double min = double.MaxValue;foreach (GasResult r in results)  {if (r.Distance < 5.0)  {double price = r.Price;if (r.Name == "Safeway")                price *= 0.9;if (price < min)                min = price;        }     }return min;}56Shahriar HyderMarch 30, 2010Kaz Software Ltd.

More Related Content

What's hot (20)

Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
Julie Iskander
 
Event handling
Event handlingEvent handling
Event handling
swapnac12
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
ThamizhselviKrishnam
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
Tech_MX
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
sameer farooq
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
International Institute of Information Technology (I²IT)
 
Python libraries
Python librariesPython libraries
Python libraries
Prof. Dr. K. Adisesha
 
C++ OOPS Concept
C++ OOPS ConceptC++ OOPS Concept
C++ OOPS Concept
Boopathi K
 
javascript objects
javascript objectsjavascript objects
javascript objects
Vijay Kalyan
 
Python functions
Python functionsPython functions
Python functions
Prof. Dr. K. Adisesha
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Vineeta Garg
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
Kamal Acharya
 
Chapter 12 ds
Chapter 12 dsChapter 12 ds
Chapter 12 ds
Hanif Durad
 
anatomy of a jsp page & jsp syntax.pptx
anatomy of a jsp page & jsp syntax.pptxanatomy of a jsp page & jsp syntax.pptx
anatomy of a jsp page & jsp syntax.pptx
Sameenafathima4
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
Taha Malampatti
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
Taha Malampatti
 
Operators in python
Operators in pythonOperators in python
Operators in python
eShikshak
 
Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)
swapnac12
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Nilesh Dalvi
 

Viewers also liked (11)

Machine Learning with Apache Mahout
Machine Learning with Apache MahoutMachine Learning with Apache Mahout
Machine Learning with Apache Mahout
Daniel Glauser
 
Modeling with Hadoop kdd2011
Modeling with Hadoop kdd2011Modeling with Hadoop kdd2011
Modeling with Hadoop kdd2011
Milind Bhandarkar
 
Functional programming
Functional programmingFunctional programming
Functional programming
Prateek Jain
 
The Lambda Calculus and The JavaScript
The Lambda Calculus and The JavaScriptThe Lambda Calculus and The JavaScript
The Lambda Calculus and The JavaScript
Norman Richards
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
Luis Atencio
 
Lambda Calculus by Dustin Mulcahey
Lambda Calculus by Dustin Mulcahey Lambda Calculus by Dustin Mulcahey
Lambda Calculus by Dustin Mulcahey
Hakka Labs
 
Interactive Scientific Image Analysis using Spark
Interactive Scientific Image Analysis using SparkInteractive Scientific Image Analysis using Spark
Interactive Scientific Image Analysis using Spark
Kevin Mader
 
Functional programming
Functional programmingFunctional programming
Functional programming
edusmildo
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
Prashant Kalkar
 
Predictive Analytics Project in Automotive Industry
Predictive Analytics Project in Automotive IndustryPredictive Analytics Project in Automotive Industry
Predictive Analytics Project in Automotive Industry
Matouš Havlena
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
tmont
 
Machine Learning with Apache Mahout
Machine Learning with Apache MahoutMachine Learning with Apache Mahout
Machine Learning with Apache Mahout
Daniel Glauser
 
Modeling with Hadoop kdd2011
Modeling with Hadoop kdd2011Modeling with Hadoop kdd2011
Modeling with Hadoop kdd2011
Milind Bhandarkar
 
Functional programming
Functional programmingFunctional programming
Functional programming
Prateek Jain
 
The Lambda Calculus and The JavaScript
The Lambda Calculus and The JavaScriptThe Lambda Calculus and The JavaScript
The Lambda Calculus and The JavaScript
Norman Richards
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
Luis Atencio
 
Lambda Calculus by Dustin Mulcahey
Lambda Calculus by Dustin Mulcahey Lambda Calculus by Dustin Mulcahey
Lambda Calculus by Dustin Mulcahey
Hakka Labs
 
Interactive Scientific Image Analysis using Spark
Interactive Scientific Image Analysis using SparkInteractive Scientific Image Analysis using Spark
Interactive Scientific Image Analysis using Spark
Kevin Mader
 
Functional programming
Functional programmingFunctional programming
Functional programming
edusmildo
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
Prashant Kalkar
 
Predictive Analytics Project in Automotive Industry
Predictive Analytics Project in Automotive IndustryPredictive Analytics Project in Automotive Industry
Predictive Analytics Project in Automotive Industry
Matouš Havlena
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
tmont
 
Ad

Similar to Functional Programming Fundamentals (20)

Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Dave Fancher
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
Konrad Szydlo
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#
Riccardo Terrell
 
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Innovecs
 
Introductory func prog
Introductory func progIntroductory func prog
Introductory func prog
Oleksandr Khomenko
 
Functional programming
Functional programmingFunctional programming
Functional programming
PiumiPerera7
 
When life gives you functions make functional programs!
When life gives you functions make functional programs!When life gives you functions make functional programs!
When life gives you functions make functional programs!
Aaron Levin
 
Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)
Omar Abdelhafith
 
Functional Programming 之二三事
Functional Programming 之二三事Functional Programming 之二三事
Functional Programming 之二三事
Leeheng Ma
 
Functional Programming #FTW
Functional Programming #FTWFunctional Programming #FTW
Functional Programming #FTW
Adriano Bonat
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming Paradigms
Directi Group
 
Functional Programming Introduction
Functional Programming IntroductionFunctional Programming Introduction
Functional Programming Introduction
Roberto Lopez
 
DEF CON 27 - workshop - EIGENTOURIST - hacking with monads
DEF CON 27 - workshop - EIGENTOURIST - hacking with monadsDEF CON 27 - workshop - EIGENTOURIST - hacking with monads
DEF CON 27 - workshop - EIGENTOURIST - hacking with monads
Felipe Prado
 
Intro f# functional_programming
Intro f# functional_programmingIntro f# functional_programming
Intro f# functional_programming
Mauro Ghiani
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming Paradigms
Janeve George
 
Evolving as a professional software developer
Evolving as a professional software developerEvolving as a professional software developer
Evolving as a professional software developer
Anton Kirillov
 
Exploring the Real Power of Functional Programming
Exploring the Real Power of Functional ProgrammingExploring the Real Power of Functional Programming
Exploring the Real Power of Functional Programming
Knoldus Inc.
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programming
Dhaval Dalal
 
Антон Кириллов, ZeptoLab
Антон Кириллов, ZeptoLabАнтон Кириллов, ZeptoLab
Антон Кириллов, ZeptoLab
Diana Dymolazova
 
Good functional programming is good programming
Good functional programming is good programmingGood functional programming is good programming
Good functional programming is good programming
kenbot
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Dave Fancher
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
Konrad Szydlo
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#
Riccardo Terrell
 
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Introduction Functional Programming - Tech Hangout #11 - 2013.01.16
Innovecs
 
Functional programming
Functional programmingFunctional programming
Functional programming
PiumiPerera7
 
When life gives you functions make functional programs!
When life gives you functions make functional programs!When life gives you functions make functional programs!
When life gives you functions make functional programs!
Aaron Levin
 
Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)
Omar Abdelhafith
 
Functional Programming 之二三事
Functional Programming 之二三事Functional Programming 之二三事
Functional Programming 之二三事
Leeheng Ma
 
Functional Programming #FTW
Functional Programming #FTWFunctional Programming #FTW
Functional Programming #FTW
Adriano Bonat
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming Paradigms
Directi Group
 
Functional Programming Introduction
Functional Programming IntroductionFunctional Programming Introduction
Functional Programming Introduction
Roberto Lopez
 
DEF CON 27 - workshop - EIGENTOURIST - hacking with monads
DEF CON 27 - workshop - EIGENTOURIST - hacking with monadsDEF CON 27 - workshop - EIGENTOURIST - hacking with monads
DEF CON 27 - workshop - EIGENTOURIST - hacking with monads
Felipe Prado
 
Intro f# functional_programming
Intro f# functional_programmingIntro f# functional_programming
Intro f# functional_programming
Mauro Ghiani
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming Paradigms
Janeve George
 
Evolving as a professional software developer
Evolving as a professional software developerEvolving as a professional software developer
Evolving as a professional software developer
Anton Kirillov
 
Exploring the Real Power of Functional Programming
Exploring the Real Power of Functional ProgrammingExploring the Real Power of Functional Programming
Exploring the Real Power of Functional Programming
Knoldus Inc.
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programming
Dhaval Dalal
 
Антон Кириллов, ZeptoLab
Антон Кириллов, ZeptoLabАнтон Кириллов, ZeptoLab
Антон Кириллов, ZeptoLab
Diana Dymolazova
 
Good functional programming is good programming
Good functional programming is good programmingGood functional programming is good programming
Good functional programming is good programming
kenbot
 
Ad

More from Shahriar Hyder (9)

Effective Communication Skills for Software Engineers
Effective Communication Skills for Software EngineersEffective Communication Skills for Software Engineers
Effective Communication Skills for Software Engineers
Shahriar Hyder
 
A JavaScript Master Class - From the Wows to the WTFs
A JavaScript Master Class - From the Wows to the WTFsA JavaScript Master Class - From the Wows to the WTFs
A JavaScript Master Class - From the Wows to the WTFs
Shahriar Hyder
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion Principle
Shahriar Hyder
 
Bridge Design Pattern
Bridge Design PatternBridge Design Pattern
Bridge Design Pattern
Shahriar Hyder
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
Shahriar Hyder
 
Taking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocketTaking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocket
Shahriar Hyder
 
Object Relational Mapping with LINQ To SQL
Object Relational Mapping with LINQ To SQLObject Relational Mapping with LINQ To SQL
Object Relational Mapping with LINQ To SQL
Shahriar Hyder
 
C# 3.0 Language Innovations
C# 3.0 Language InnovationsC# 3.0 Language Innovations
C# 3.0 Language Innovations
Shahriar Hyder
 
Introduction to Linq
Introduction to LinqIntroduction to Linq
Introduction to Linq
Shahriar Hyder
 
Effective Communication Skills for Software Engineers
Effective Communication Skills for Software EngineersEffective Communication Skills for Software Engineers
Effective Communication Skills for Software Engineers
Shahriar Hyder
 
A JavaScript Master Class - From the Wows to the WTFs
A JavaScript Master Class - From the Wows to the WTFsA JavaScript Master Class - From the Wows to the WTFs
A JavaScript Master Class - From the Wows to the WTFs
Shahriar Hyder
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion Principle
Shahriar Hyder
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
Shahriar Hyder
 
Taking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocketTaking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocket
Shahriar Hyder
 
Object Relational Mapping with LINQ To SQL
Object Relational Mapping with LINQ To SQLObject Relational Mapping with LINQ To SQL
Object Relational Mapping with LINQ To SQL
Shahriar Hyder
 
C# 3.0 Language Innovations
C# 3.0 Language InnovationsC# 3.0 Language Innovations
C# 3.0 Language Innovations
Shahriar Hyder
 

Recently uploaded (20)

Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0
RodrigoMori7
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Soulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate reviewSoulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate review
Soulmaite
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | BluebashMCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
Bluebash
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Dancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptxDancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptx
Elliott Richmond
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0
RodrigoMori7
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Soulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate reviewSoulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate review
Soulmaite
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | BluebashMCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
MCP vs A2A vs ACP: Choosing the Right Protocol | Bluebash
Bluebash
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Dancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptxDancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptx
Elliott Richmond
 

Functional Programming Fundamentals

  • 1. Functional Programming FundamentalsElements of Functional Programmingl1Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 2. ”Life is too short for imperative programming”John Hughes2Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 3. Productivity“It’s really clear that the imperative style of programming has run its course. ... We’re sort of done with that. … However, in the declarative realm we can speculate a 10x improvement in productivity in certain domains.”Anders Hejlsberg C# Architect(from his MIX07 keynote)3Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 4. Origins4Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 5. Originsfunctional programming emerged slightly by accident from several sourcessymbolic logic, specifically the l-calculus (A.Church 1930s) and combinatory logic (H.Curry 1930s) λop.λx.(op x x) (λop.λx.(op x x)) (+) 21 = (λx.((+) x x)) 21 = (+) 21 21 = 42the symbolic manipulation strand of Artificial Intelligence, or rather: LISP (J.McCarthy 1960)pseudo-code for CS publications, ISWIM (P.Landin 1966)support languages for logic and mathematics, e.g. LCF’s metalanguageML (Milner et. al. 1970s)OCaml – 1996F# (and parts of C#) – 20025Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 6. λ-calculus Building BlockAnonymous functions SupportJavaScriptPHP 4.0.1 – PHP 5.2.x (kinda)PHP 5.3 (more kinda)C# 2.0Java – Hardly any support. Anonymous Classes to use Closures. Java also supports another form of classes, which are called inner (or nested) classes. These are defined in the body of an enclosing class and have full access to each and every instance variable of the enclosing class, thus resembling standard function closures. 6Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 7. Fundamentals of FP LanguagesThe objective of the design of a FPL is to mimic mathematical functions to the greatest extent possibleThe basic process of computation is fundamentally different in a FPL than in an imperative languageIn an imperative language, operations are done and the results are stored in variables for later useManagement of variables is a constant concern and source of complexity for imperative programmingIn an FPL, variables are not necessary, as is the case in mathematics7Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 8. What is object-oriented programming?Object-oriented programming is a style of programming that enables you: - Reuse code (via classes) - Eliminate bugs (via encapsulating, data hiding)8Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 9. What is functional programming?Functional programming is a style of programming that enables you: - Re-use code (via function composition) - Eliminate bugs (via immutability)9Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 10. Moore’s Law Ran Out!10Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 11. “Software gets slower faster than hardware gets faster” --Wirth’s Law11Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 12. Von Neumann syndromeFor most applications in massively parallel computing systems with thousands or tens of thousands of processors the performance can be less than hoped. Sometimes called a "supercomputing crisis" it is believed to be due to two factors. Firstly a hardware barrier in the efficiency in moving data, called the memory wall or von Neumann bottleneck (An inefficiency inherent in the design of any von Neumann machine [The von Neumann architecture is a design model for a stored-program digital computer that uses a central processing unit (CPU) and a single separate storage structure ("memory") to hold both instructions and data. It has a sequential architecture.]that arises from the fact that most computer time is spent in moving information between storage and the central processing unit rather than operating on it. ). Secondly a fall in programmer productivity when faced with systems that are massively parallel, the difficulties in developing for parallelism (or thread-level parallelism in multi-core CPUs) when previously this was not an issue.12Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 13. Wikipedia!In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state. Functional programming has its roots in the lambda calculus, a formal system developed in the 1930s to investigate function definition, function application, and recursion. Many functional programming languages can be viewed as elaborations on the lambda calculus.In practice, the difference between a mathematical function and the notion of a "function" used in imperative programming is that imperative functions can have side effects, changing the value of already calculated computations. Because of this they lack referential transparency, i.e. the same language expression can result in different values at different times depending on the state of the executing program. Conversely, in functional code, the output value of a function depends only on the arguments that are input to the function, so calling a function f twice with the same value for an argument x will produce the same result f(x) both times. Eliminating side-effects can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development of functional programming.13
  • 14. 14Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 15. 15Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 16. 16Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 17. 17Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 18. 18Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 19. 19Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 20. 20Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 21. 21Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 22. Functional LanguagesHaskellCleanF#ML / OCamlLisp / SchemeScala
  • 24. XSLT
  • 26. SQL
  • 27. Mathematica22Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 28. Pure Functional LanguagesHaskellCleanF#ML / OCamlLisp / SchemeScala
  • 30. XSLT
  • 32. SQL
  • 33. MathematicaPurely functional is a term in computing used to describe algorithms, data structures or programming languages that exclude destructive modifications (updates). According to this restriction, variables are used in a mathematical sense, with identifiers referring to immutable, persistent values.23Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 34. Is it too hard?24Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 35. The foundation25Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 36. What is a function?y = f(x)26Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 37. FP Preachings!Avoid Side-Effects!Do not modify variables passed to themDo not modify any global variable27Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 38. FP Preachings!Avoid Mutation!“Mutation Considered Harmful” 28Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 39. FP Preachings!Variables only assigned onceSame input -> Same outputFunctions return valuesGiven a set of values in the parameter list, the function can only have one possible result.No Shared State29Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 40. FP Preachings!Does order matter?Order is a side effect as well..30Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 41. Functional ProgrammingFocus on results not processEmphasis is on what is to be computed not how it HappensData is immutableFunctions are data tooDecompose problem into ‘functions’31Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 42. Data is immutablex = x + 1;Why should a function in C never return a pointer?Why should you make a copy of an internal array before returning it from your class?Why is multi-threading so damn hard?32Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 43. Why bother?Pure functions can be executed in parallel without interfering with one anotherPure functions can be “perfectly” cachedPure functions can be “partially” appliedFunctions can receive and return functions, for which all of the above hold trueAllows for greater “modularity” and “composability”33Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 44. Code!//F#openSystemlet a = 2Console.WriteLine a//C#using System;namespace ConsoleApplication1{classProgram{staticint a(){return 2;}static void Main(string[] args){Console.WriteLine(a); }}}34Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 45. More Code!//F#openSystemlet a = 2Console.WriteLine a//C#using System;namespace ConsoleApplication1{classProgram{static nta(){return2;}static void Main(string[] args){Console.WriteLine(a); }}}More Noise Than Signal!35Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 46. Refactoring “hole in the middle”Header() { ■ ■ ■ }Footer() { ■ ■ ■ }Red() { ■ ■■ }Blue() { ■ ■■ }Foo(){ Header();Red(); Footer();}Bar(){ Header();Blue(); Footer();}Factor out the differences and the similarities?!36Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 47. Refactoring “hole in the middle”Red() { ■ ■■ }Blue() { ■ ■■ }FooBar(func){■ ■ ■func();■ ■ ■}The “FP Way” is to simply pass in an implementation of the “hole” to be filled:FooBar( {■ ■■});37Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 48. Example: Sorting by multiple keysclassGasResult{publicGasResult(…) { … }publicreadonlystring Name;publicreadonlydouble Price;publicreadonlydouble Distance;}Problem: You want to sort lists of GasResults by various keys.38Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 49. OO Approach: Many IComparersclassGasResult{ …publicclassGasPriceComparer : IComparer<GasResult> { publicint Compare(GasResult a, GasResult b) { returna.Price.CompareTo(b.Price); } }publicstaticGasPriceComparerGasPriceComparison =newGasPriceComparer();}Array.Sort<GasResult>(results, GasResult.GasPriceComparison);39Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 50. OO Approach: Many IComparersclassGasResult{ …publicclassGasNameComparer : IComparer<GasResult> { publicint Compare(GasResult a, GasResult b) { returna.Name.CompareTo(b.Name); } }publicstaticGasNameComparerGasNameComparison =newGasNameComparer();}Array.Sort<GasResult>(results, GasResult.GasNameComparison);40Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 51. OO Approach: Many IComparersclassGasResult{ …publicclassGasDistanceComparer : IComparer<GasResult> { publicint Compare(GasResult a, GasResult b) { returna.Distance.CompareTo(b.Distance); } }publicstaticGasDistanceComparerGasDistanceComparison =newGasDistanceComparer();}Array.Sort<GasResult>(results, GasResult.GasDistanceComparison);41Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 52. FP Approach: Passed in lambdasclassGasResult{ …}results.OrderBy<GasResult,double>(r => r.Price);results.OrderBy<GasResult,string>(r => r.Name);results.OrderBy<GasResult,double>(r => r.Distance);(extension) IOrderedSequence<TSource>IEnumerable<TSource>.OrderBy<TSource, TKey>(Func<TSource, Tkey> keySelector)42Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 53. 43Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 54. First-class functionIn computer science, a programming language is said to support first-class functions if it treats functions as first-class objects. Specifically, this means that the language supports constructing new functions during the execution of a program, storing them in data structures, passing them as arguments to other functions, and returning them as the values of other functions.44Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 55. Closure (computer science)In computer science, a closure is a first-class function with free variables that are bound in the lexical environment. Such a function is said to be "closed over" its free variables. A closure is defined within the scope of its free variables, and the extent of those variables is at least as long as the lifetime of the closure itself..45Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 56. Closures46Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 57. Closure exampleHere is an example rewritten in ECMAScript (JavaScript) : // Return a list of all books with at least 'threshold' copies sold. function bestSellingBooks(threshold) { returnbookList.filter( function (book) {returnbook.sales >= threshold; } ); }A function may create a closure and return it, as in the following example: // Return a function that approximates the derivative of f // using an interval of dx, which should be appropriately small. function derivative(f, dx) { return function (x) { return (f(x + dx) - f(x)) / dx; };}Because the closure in this case outlives the scope of the function that creates it, the variables f and dx live on after the function derivative returns. In languages without closures, the lifetime of a local variable coincides with the execution of the scope where that variable is declared. In languages with closures, variables must continue to exist as long as any existing closures have references to them. This is most commonly implemented using some form of garbage collection.47Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 58. Generators/* Method that takes an iterable input (possibly an array) and returns all even numbers. */ publicstaticIEnumerable<int> GetEven(IEnumerable<int> numbers) { foreach (intiin numbers) { if ((i % 2) == 0) { yieldreturni; } } } You may even use multiple yield return statements and the compiler will return them in order on each iteration:publicclassCityCollection : IEnumerable<string> {publicIEnumerator<string> GetEnumerator() { yieldreturn"New York"; yieldreturn"Paris"; yieldreturn"London"; } }48Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 59. Higher order functions Higher-order functions are closely related to first-class functions, in that higher-order functions and first-class functions both allow functions as arguments and results of other functions. The distinction between the two is subtle: "higher-order" describes a mathematical concept of functions that operate on other functions, while "first-class" is a computer science term that describes programming language entities that have no restriction on their use (thus first-class functions can appear anywhere in the program that other first-class entities like numbers can, including as arguments to other functions and as their return values).49Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 60. Higher order function example//f is a function function derivative(f) { return function(x) { //approximation of derivative return (f(x + 0.00001) f(x)) / 0.00001;      } } 50Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 61. Higher order function example//evaluate derivative of x2: varderiv_x_squared = derivative(     function(x) {         return x*x;     } ); alert(deriv_x_squared(3)); //alerts 6ish51Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 62. 52Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 63. 53Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 64. 54Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 65. 55Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 66. Map/Reduce/FilterdoubleCheapGasNearby(IEnumerable<GasResult> results) {double min = double.MaxValue;foreach (GasResult r in results) {if (r.Distance < 5.0) {double price = r.Price;if (r.Name == "Safeway") price *= 0.9;if (price < min) min = price; } }return min;}56Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 67. Map/Reduce/FilterdoubleCheapGasNearby(IEnumerable<GasResult> results) {double min = double.MaxValue;foreach (GasResult r in results) {if (r.Distance < 5.0) {double price = r.Price;if (r.Name == "Safeway") price *= 0.9;if (price < min) min = price; } }return min;}57Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 68. Map/Reduce/FilterdoubleCheapGasNearby(IEnumerable<GasResult> results) {double min = double.MaxValue;foreach (GasResult r in results) {if (r.Distance < 5.0) {double price = r.Price;if (r.Name == "Safeway") price *= 0.9;if (price < min) min = price; } }return min;}58Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 69. Map/Reduce/FilterdoubleCheapGasNearby(IEnumerable<GasResult> results) {double min = double.MaxValue;foreach (GasResult r in results) {if (r.Distance < 5.0) {double price = r.Price;if (r.Name == "Safeway") price *= 0.9;if (price < min) min = price;} }return min;}59Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 70. Map/Reduce/FilterdoubleCheapGasNearby(IEnumerable<GasResult> results){results.Where(r => r.Distance < 5.0).Select(r => r.Price * (r.Name == "Safeway" ? 0.9 : 1.0)).Aggregate(double.MaxValue, (m, p) => p < m ? p : m));}.Where<GasResult>(Func<GasResult, bool> predicate).Select<GasResult, double>(Func<GasResult, double> mapping).Aggregate<double, double>(double seed, Func<double, double, double> func)60Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 71. Map/Reduce/FilterdoubleCheapGasNearby(IEnumerable<GasResult> results){results.Where(r => r.Distance < 5.0).Select(r => r.Price * (r.Name == "Safeway" ? 0.9 : 1.0)) .Min();}.Where<GasResult>(Func<GasResult, bool> predicate).Select<GasResult, double>(Func<GasResult, double> mapping).Aggregate<double, double>(double seed, Func<double, double, double> func)61Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 72. Map/Reduce/FilterdoubleCheapGasNearby(IEnumerable<GasResult> results){ (from r in resultswherer.Distance < 5.0selectr.Price * (r.Name == "Safeway" ? 0.9 : 1.0) ).Min()}.Where<GasResult>(Func<GasResult, bool> predicate).Select<GasResult, double>(Func<GasResult, double> mapping).Aggregate<double, double>(double seed, Func<double, double, double> func)62Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 73. 63Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 74. SummaryPure functionsWorking without assignmentRecursion rather than for/while/etc.Higher-order functionsPower! Brevity! Beautiful!Hole in the middleCompositionalBecoming mainstreamDriven by concurrencyMore productivity regardless64Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 75. QuizIs ”2+2” equal to ”4”?65Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 76. ReferenceF#http://research.microsoft.com/fsharpCan Your Programming Language Do This?http://www.joelonsoftware.com/items/2006/08/01.htmlWhy Functional Programming Mattershttp://www.math.chalmers.se/~rjmh/Papers/whyfp.pdfJohn Backus’ 1977 Turing Award Lecture:“Can Programming be Liberated from the von Neumann Style?”System.Concurrency Libraryhttp://msdn.microsoft.com/msdnmag/issues/07/10/Futures/default.aspxGoogle MapReducehttp://labs.google.com/papers/mapreduce.html66Shahriar HyderMarch 30, 2010Kaz Software Ltd.
  • 77. 67End of the TalkThank You!Questions?Shahriar HyderMarch 30, 2010Kaz Software Ltd.

Editor's Notes

  • #40: IComparer is a heavy-weight function pointer to Compare()
  • #43: Could instead have an Order() method taking a Func&lt;T, U, int&gt;; essentially passing in Compare()Instead, here we’re passing in a selector and expecting the individual keys to be IComparable
  • #57: Ahhhh! Mutation and mixing of intent all over the place!
  • #61: Separation of concerns.No assignment.Solution assembled from already well-tested compositional units.
  • #62: Min() is really a specialization of filter
  • #63: Using LINQ syntax is nice, but not necessary.Note: LINQ is for querying collections (or anything IEnumerable / IQueryable) not necessarily anything to do with SQL.