The document discusses the fundamentals of functional programming, highlighting its origins from symbolic logic and lambda calculus, and contrasts it with imperative programming. It emphasizes key principles such as immutability, avoidance of side effects, and the use of first-class and higher-order functions in creating more modular and composable code. The content also addresses practical aspects of functional programming through examples and comparisons with object-oriented programming.
”Life is tooshort for imperative programming”John Hughes2Shahriar HyderMarch 30, 2010Kaz Software Ltd.
3.
Productivity“It’s really clearthat 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.
Originsfunctional programming emergedslightly 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 BlockAnonymousfunctions 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 FPLanguagesThe 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-orientedprogramming?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 functionalprogramming?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 RanOut!10Shahriar HyderMarch 30, 2010Kaz Software Ltd.
Von Neumann syndromeFormost 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
MathematicaPurely functional isa 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 toohard?24Shahriar HyderMarch 30, 2010Kaz Software Ltd.
FP Preachings!Variables onlyassigned 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 ordermatter?Order is a side effect as well..30Shahriar HyderMarch 30, 2010Kaz Software Ltd.
41.
Functional ProgrammingFocus onresults 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 functionscan 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.
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 inthe 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 inthe 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 bymultiple 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.
First-class functionIn computerscience, 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)Incomputer 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.
Closure exampleHere isan 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 thattakes 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 functionexample//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.
SummaryPure functionsWorking withoutassignmentRecursion rather than for/while/etc.Higher-order functionsPower! Brevity! Beautiful!Hole in the middleCompositionalBecoming mainstreamDriven by concurrencyMore productivity regardless64Shahriar HyderMarch 30, 2010Kaz Software Ltd.
ReferenceF#http://research.microsoft.com/fsharpCan Your ProgrammingLanguage 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 theTalkThank 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<T, U, int>; 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.
#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.