SlideShare a Scribd company logo
1 of 66
Functional Programming Fundamentals Elements of Functional Programming l 1 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
”Life is too short for imperative programming” John Hughes 2 Shahriar Hyder March 30, 2010 Kaz 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. ” ,[object Object],(from his MIX07 keynote) 3 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
Origins 4 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
Origins functional programming emerged slightly by accident from several sources symbolic 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 = 42 the 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 – 1996 F# (and parts of C#) – 2002 5 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
λ-calculus Building Block Anonymous functions Support JavaScript PHP 4.0.1 – PHP 5.2.x (kinda) PHP 5.3 (more kinda) C# 2.0 Java – 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.  6 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
Fundamentals of FP Languages The objective of the design of a FPL is to mimic mathematical functions to the greatest extent possible The basic process of computation is fundamentally different in a FPL than in an imperative language In an imperative language, operations are done and the results are stored in variables for later use Management of variables is a constant concern and source of complexity for imperative programming In an FPL, variables are not necessary, as is the case in mathematics 7 Shahriar Hyder March 30, 2010 Kaz 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) 8 Shahriar Hyder March 30, 2010 Kaz 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) 9 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
Moore’s Law Ran Out! 10 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
“Software gets slower faster than hardware gets faster” 							--Wirth’s Law 11 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
Von Neumann syndrome For 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. 12 Shahriar Hyder March 30, 2010 Kaz 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
14 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
15 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
16 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
17 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
18 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
19 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
20 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
21 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
Functional Languages Haskell Clean F# ML / OCaml Lisp / Scheme ,[object Object]
Clojure
XSLT
Erlang
SQL
Mathematica22 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
Pure Functional Languages Haskell Clean F# ML / OCaml Lisp / Scheme ,[object Object]
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. 23 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
Is it too hard? 24 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
The foundation 25 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
What is a function? y = f(x) 26 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
FP Preachings! Avoid Side-Effects! Do not modify variables passed to them Do not modify any global variable 27 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
FP Preachings! Avoid Mutation! “Mutation Considered Harmful”  28 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
FP Preachings! Variables only assigned once Same input -> Same output Functions return values Given a set of values in the parameter list, the function can only have one possible result. No Shared State 29 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
FP Preachings! Does order matter? Order is a side effect as well.. 30 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
Functional Programming Focus on results not process Emphasis is on what is to be computed not how it Happens Data is immutable Functions are data too Decompose problem into ‘functions’ 31 Shahriar Hyder March 30, 2010 Kaz 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? 32 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
Why bother? Pure functions can be executed in parallel without interfering with one another Pure functions can be “perfectly” cached Pure functions can be “partially” applied Functions can receive and return functions, for which all of the above hold true Allows for greater “modularity” and “composability” 33 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
Code! //F# openSystem let a = 2 Console.WriteLine a //C# using System; namespace ConsoleApplication1 { classProgram { staticint a() { return 2; } static void Main(string[] args) { Console.WriteLine(a);             } } } 34 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
More Code! //F# openSystem let a = 2 Console.WriteLine a //C# using System; namespace ConsoleApplication1 { classProgram { static nta() { return2; } static void Main(string[] args) { Console.WriteLine(a);             } } } More Noise  Than Signal! 35 Shahriar Hyder March 30, 2010 Kaz 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?! 36 Shahriar Hyder March 30, 2010 Kaz 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( {■ ■■}); 37 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
Example: Sorting by multiple keys classGasResult{publicGasResult(…)  { … }publicreadonlystring Name;publicreadonlydouble Price;publicreadonlydouble Distance;} Problem: You want to sort lists of GasResults by various keys. 38 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
OO Approach: Many IComparers classGasResult{     …publicclassGasPriceComparer : IComparer<GasResult>    {   publicint Compare(GasResult a, GasResult b)        {   returna.Price.CompareTo(b.Price);   }   }publicstaticGasPriceComparerGasPriceComparison =newGasPriceComparer();} Array.Sort<GasResult>(results, GasResult.GasPriceComparison); 39 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
OO Approach: Many IComparers classGasResult{     …publicclassGasNameComparer : IComparer<GasResult>    {   publicint Compare(GasResult a, GasResult b)        {   returna.Name.CompareTo(b.Name);   }   }publicstaticGasNameComparerGasNameComparison =newGasNameComparer();} Array.Sort<GasResult>(results,  GasResult.GasNameComparison); 40 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
OO Approach: Many IComparers classGasResult{     …publicclassGasDistanceComparer : IComparer<GasResult>    {   publicint Compare(GasResult a, GasResult b)        {   returna.Distance.CompareTo(b.Distance);   }   }publicstaticGasDistanceComparerGasDistanceComparison =newGasDistanceComparer();} Array.Sort<GasResult>(results, GasResult.GasDistanceComparison); 41 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
FP Approach: Passed in lambdas classGasResult{     …} 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) 42 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
43 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
First-class function In 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. 44 Shahriar Hyder March 30, 2010 Kaz 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.. 45 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
Closures 46 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
Closure example Here 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. 47 Shahriar Hyder March 30, 2010 Kaz 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";  }  } 48 Shahriar Hyder March 30, 2010 Kaz 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). 49 Shahriar Hyder March 30, 2010 Kaz 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;     	} }  50 Shahriar Hyder March 30, 2010 Kaz 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 6ish 51 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
52 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
53 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
54 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
55 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
Map/Reduce/Filter doubleCheapGasNearby(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;} 56 Shahriar Hyder March 30, 2010 Kaz Software Ltd.

More Related Content

What's hot

What's hot (20)

Introduction to c++ ppt 1
Introduction to c++ ppt 1Introduction to c++ ppt 1
Introduction to c++ ppt 1
 
Inheritance in OOPS
Inheritance in OOPSInheritance in OOPS
Inheritance in OOPS
 
Abstract Class Presentation
Abstract Class PresentationAbstract Class Presentation
Abstract Class Presentation
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented Programming
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Operators in C++
Operators in C++Operators in C++
Operators in C++
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Context free grammar
Context free grammar Context free grammar
Context free grammar
 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
 
Oops concept in c++ unit 3 -topic 4
Oops concept in c++ unit 3 -topic 4Oops concept in c++ unit 3 -topic 4
Oops concept in c++ unit 3 -topic 4
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptx
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Searching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data StructureSearching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data Structure
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
C if else
C if elseC if else
C if else
 
Interface in java
Interface in javaInterface in java
Interface in java
 

Viewers also liked

Machine Learning with Apache Mahout
Machine Learning with Apache MahoutMachine Learning with Apache Mahout
Machine Learning with Apache Mahout
Daniel Glauser
 
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
 

Viewers also liked (11)

Machine Learning with Apache Mahout
Machine Learning with Apache MahoutMachine Learning with Apache Mahout
Machine Learning with Apache Mahout
 
Modeling with Hadoop kdd2011
Modeling with Hadoop kdd2011Modeling with Hadoop kdd2011
Modeling with Hadoop kdd2011
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
The Lambda Calculus and The JavaScript
The Lambda Calculus and The JavaScriptThe Lambda Calculus and The JavaScript
The Lambda Calculus and The JavaScript
 
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
 
Lambda Calculus by Dustin Mulcahey
Lambda Calculus by Dustin Mulcahey Lambda Calculus by Dustin Mulcahey
Lambda Calculus by Dustin Mulcahey
 
Interactive Scientific Image Analysis using Spark
Interactive Scientific Image Analysis using SparkInteractive Scientific Image Analysis using Spark
Interactive Scientific Image Analysis using Spark
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Predictive Analytics Project in Automotive Industry
Predictive Analytics Project in Automotive IndustryPredictive Analytics Project in Automotive Industry
Predictive Analytics Project in Automotive Industry
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
 

Similar to Functional Programming Fundamentals

BTE 320-498 Summer 2017 Take Home Exam (200 poi.docx
BTE 320-498 Summer 2017 Take Home Exam (200 poi.docxBTE 320-498 Summer 2017 Take Home Exam (200 poi.docx
BTE 320-498 Summer 2017 Take Home Exam (200 poi.docx
AASTHA76
 
London F-Sharp User Group : Don Syme on F# - 09/09/2010
London F-Sharp User Group : Don Syme on F# - 09/09/2010London F-Sharp User Group : Don Syme on F# - 09/09/2010
London F-Sharp User Group : Don Syme on F# - 09/09/2010
Skills Matter
 
Distributed computing poli
Distributed computing poliDistributed computing poli
Distributed computing poli
ivascucristian
 
Programming Languages - Functional Programming Paper
Programming Languages - Functional Programming PaperProgramming Languages - Functional Programming Paper
Programming Languages - Functional Programming Paper
Shreya Chakrabarti
 

Similar to Functional Programming Fundamentals (20)

Software used in Electronics and Communication
Software used in Electronics and CommunicationSoftware used in Electronics and Communication
Software used in Electronics and Communication
 
On being a professional software developer
On being a professional software developerOn being a professional software developer
On being a professional software developer
 
Антон Кириллов, ZeptoLab
Антон Кириллов, ZeptoLabАнтон Кириллов, ZeptoLab
Антон Кириллов, ZeptoLab
 
Evolving as a professional software developer
Evolving as a professional software developerEvolving as a professional software developer
Evolving as a professional software developer
 
PRELIM-Lesson-2.pdf
PRELIM-Lesson-2.pdfPRELIM-Lesson-2.pdf
PRELIM-Lesson-2.pdf
 
BTE 320-498 Summer 2017 Take Home Exam (200 poi.docx
BTE 320-498 Summer 2017 Take Home Exam (200 poi.docxBTE 320-498 Summer 2017 Take Home Exam (200 poi.docx
BTE 320-498 Summer 2017 Take Home Exam (200 poi.docx
 
London F-Sharp User Group : Don Syme on F# - 09/09/2010
London F-Sharp User Group : Don Syme on F# - 09/09/2010London F-Sharp User Group : Don Syme on F# - 09/09/2010
London F-Sharp User Group : Don Syme on F# - 09/09/2010
 
Distributed computing poli
Distributed computing poliDistributed computing poli
Distributed computing poli
 
STAT-522 (Data Analysis Using R) by SOUMIQUE AHAMED.pdf
STAT-522 (Data Analysis Using R) by SOUMIQUE AHAMED.pdfSTAT-522 (Data Analysis Using R) by SOUMIQUE AHAMED.pdf
STAT-522 (Data Analysis Using R) by SOUMIQUE AHAMED.pdf
 
Summer training in matlab
Summer training in matlabSummer training in matlab
Summer training in matlab
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 
Software
SoftwareSoftware
Software
 
SE1.ppt
SE1.pptSE1.ppt
SE1.ppt
 
Aspect Oriented Programming Through C#.NET
Aspect Oriented Programming Through C#.NETAspect Oriented Programming Through C#.NET
Aspect Oriented Programming Through C#.NET
 
What is algorithm
What is algorithmWhat is algorithm
What is algorithm
 
Introduction to F#
Introduction to F#Introduction to F#
Introduction to F#
 
Programming Languages - Functional Programming Paper
Programming Languages - Functional Programming PaperProgramming Languages - Functional Programming Paper
Programming Languages - Functional Programming Paper
 
ArduinoWorkshop2.pdf
ArduinoWorkshop2.pdfArduinoWorkshop2.pdf
ArduinoWorkshop2.pdf
 
Best corporate-r-programming-training-in-mumbai
Best corporate-r-programming-training-in-mumbaiBest corporate-r-programming-training-in-mumbai
Best corporate-r-programming-training-in-mumbai
 
Recommendations for Building Machine Learning Software
Recommendations for Building Machine Learning SoftwareRecommendations for Building Machine Learning Software
Recommendations for Building Machine Learning Software
 

More from Shahriar Hyder

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
 
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
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion Principle
 
Bridge Design Pattern
Bridge Design PatternBridge Design Pattern
Bridge Design Pattern
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
 
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
 
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
 
C# 3.0 Language Innovations
C# 3.0 Language InnovationsC# 3.0 Language Innovations
C# 3.0 Language Innovations
 
Introduction to Linq
Introduction to LinqIntroduction to Linq
Introduction to Linq
 

Recently uploaded

Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
UXDXConf
 

Recently uploaded (20)

Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
The UX of Automation by AJ King, Senior UX Researcher, Ocado
The UX of Automation by AJ King, Senior UX Researcher, OcadoThe UX of Automation by AJ King, Senior UX Researcher, Ocado
The UX of Automation by AJ King, Senior UX Researcher, Ocado
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101
 
Designing for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastDesigning for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at Comcast
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
Connecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKConnecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAK
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 

Functional Programming Fundamentals

  • 1. Functional Programming Fundamentals Elements of Functional Programming l 1 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 2. ”Life is too short for imperative programming” John Hughes 2 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 3.
  • 4. Origins 4 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 5. Origins functional programming emerged slightly by accident from several sources symbolic 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 = 42 the 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 – 1996 F# (and parts of C#) – 2002 5 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 6. λ-calculus Building Block Anonymous functions Support JavaScript PHP 4.0.1 – PHP 5.2.x (kinda) PHP 5.3 (more kinda) C# 2.0 Java – 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. 6 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 7. Fundamentals of FP Languages The objective of the design of a FPL is to mimic mathematical functions to the greatest extent possible The basic process of computation is fundamentally different in a FPL than in an imperative language In an imperative language, operations are done and the results are stored in variables for later use Management of variables is a constant concern and source of complexity for imperative programming In an FPL, variables are not necessary, as is the case in mathematics 7 Shahriar Hyder March 30, 2010 Kaz 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) 8 Shahriar Hyder March 30, 2010 Kaz 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) 9 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 10. Moore’s Law Ran Out! 10 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 11. “Software gets slower faster than hardware gets faster” --Wirth’s Law 11 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 12. Von Neumann syndrome For 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. 12 Shahriar Hyder March 30, 2010 Kaz 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. 14 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 15. 15 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 16. 16 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 17. 17 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 18. 18 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 19. 19 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 20. 20 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 21. 21 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 22.
  • 24. XSLT
  • 26. SQL
  • 27. Mathematica22 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 28.
  • 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. 23 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 34. Is it too hard? 24 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 35. The foundation 25 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 36. What is a function? y = f(x) 26 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 37. FP Preachings! Avoid Side-Effects! Do not modify variables passed to them Do not modify any global variable 27 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 38. FP Preachings! Avoid Mutation! “Mutation Considered Harmful”  28 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 39. FP Preachings! Variables only assigned once Same input -> Same output Functions return values Given a set of values in the parameter list, the function can only have one possible result. No Shared State 29 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 40. FP Preachings! Does order matter? Order is a side effect as well.. 30 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 41. Functional Programming Focus on results not process Emphasis is on what is to be computed not how it Happens Data is immutable Functions are data too Decompose problem into ‘functions’ 31 Shahriar Hyder March 30, 2010 Kaz 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? 32 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 43. Why bother? Pure functions can be executed in parallel without interfering with one another Pure functions can be “perfectly” cached Pure functions can be “partially” applied Functions can receive and return functions, for which all of the above hold true Allows for greater “modularity” and “composability” 33 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 44. Code! //F# openSystem let a = 2 Console.WriteLine a //C# using System; namespace ConsoleApplication1 { classProgram { staticint a() { return 2; } static void Main(string[] args) { Console.WriteLine(a); } } } 34 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 45. More Code! //F# openSystem let a = 2 Console.WriteLine a //C# using System; namespace ConsoleApplication1 { classProgram { static nta() { return2; } static void Main(string[] args) { Console.WriteLine(a); } } } More Noise Than Signal! 35 Shahriar Hyder March 30, 2010 Kaz 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?! 36 Shahriar Hyder March 30, 2010 Kaz 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( {■ ■■}); 37 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 48. Example: Sorting by multiple keys classGasResult{publicGasResult(…) { … }publicreadonlystring Name;publicreadonlydouble Price;publicreadonlydouble Distance;} Problem: You want to sort lists of GasResults by various keys. 38 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 49. OO Approach: Many IComparers classGasResult{ …publicclassGasPriceComparer : IComparer<GasResult> { publicint Compare(GasResult a, GasResult b) { returna.Price.CompareTo(b.Price); } }publicstaticGasPriceComparerGasPriceComparison =newGasPriceComparer();} Array.Sort<GasResult>(results, GasResult.GasPriceComparison); 39 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 50. OO Approach: Many IComparers classGasResult{ …publicclassGasNameComparer : IComparer<GasResult> { publicint Compare(GasResult a, GasResult b) { returna.Name.CompareTo(b.Name); } }publicstaticGasNameComparerGasNameComparison =newGasNameComparer();} Array.Sort<GasResult>(results, GasResult.GasNameComparison); 40 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 51. OO Approach: Many IComparers classGasResult{ …publicclassGasDistanceComparer : IComparer<GasResult> { publicint Compare(GasResult a, GasResult b) { returna.Distance.CompareTo(b.Distance); } }publicstaticGasDistanceComparerGasDistanceComparison =newGasDistanceComparer();} Array.Sort<GasResult>(results, GasResult.GasDistanceComparison); 41 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 52. FP Approach: Passed in lambdas classGasResult{ …} 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) 42 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 53. 43 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 54. First-class function In 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. 44 Shahriar Hyder March 30, 2010 Kaz 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.. 45 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 56. Closures 46 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 57. Closure example Here 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. 47 Shahriar Hyder March 30, 2010 Kaz 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"; } } 48 Shahriar Hyder March 30, 2010 Kaz 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). 49 Shahriar Hyder March 30, 2010 Kaz 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;      } } 50 Shahriar Hyder March 30, 2010 Kaz 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 6ish 51 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 62. 52 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 63. 53 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 64. 54 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 65. 55 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 66. Map/Reduce/Filter doubleCheapGasNearby(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;} 56 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 67. Map/Reduce/Filter doubleCheapGasNearby(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;} 57 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 68. Map/Reduce/Filter doubleCheapGasNearby(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;} 58 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 69. Map/Reduce/Filter doubleCheapGasNearby(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;} 59 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 70. Map/Reduce/Filter doubleCheapGasNearby(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) 60 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 71. Map/Reduce/Filter doubleCheapGasNearby(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) 61 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 72. Map/Reduce/Filter doubleCheapGasNearby(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) 62 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 73. 63 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 74. Summary Pure functions Working without assignment Recursion rather than for/while/etc. Higher-order functions Power! Brevity! Beautiful! Hole in the middle Compositional Becoming mainstream Driven by concurrency More productivity regardless 64 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 75. Quiz Is ”2+2” equal to ”4”? 65 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 76. Reference F#http://research.microsoft.com/fsharp Can Your Programming Language Do This?http://www.joelonsoftware.com/items/2006/08/01.html Why Functional Programming Mattershttp://www.math.chalmers.se/~rjmh/Papers/whyfp.pdf John 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.aspx Google MapReducehttp://labs.google.com/papers/mapreduce.html 66 Shahriar Hyder March 30, 2010 Kaz Software Ltd.
  • 77. 67 End of the Talk Thank You! Questions? Shahriar Hyder March 30, 2010 Kaz Software Ltd.

Editor's Notes

  1. IComparer is a heavy-weight function pointer to Compare()
  2. 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
  3. Ahhhh! Mutation and mixing of intent all over the place!
  4. Separation of concerns.No assignment.Solution assembled from already well-tested compositional units.
  5. Min() is really a specialization of filter
  6. 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.