Functional pogramming hl overview
-
Upload
elad-avneri -
Category
Software
-
view
23 -
download
1
Transcript of Functional pogramming hl overview
Copyright © SELA Software & Education Labs, Ltd. | 14-18 Baruch Hirsch St., Bnei Brak 51202, Israel | www.selagroup.com
Functional Programming
High Level Introduction
http://il.linkedin.com/in/eladavneri/
http://blogs.microsoft.co.il/elada
Elad AvneriArchitect, ALM and Software Development
Agenda
The BasicsPrinciplesFP Languages
FeaturesComparison
Demo: Imperative to FP Evolution
3
Software Development Challenges
Modern software becomes larger and more complexWe’d like to reduce the time and cost of software developmentWe’d like to increase the quality of the developed software
FP to the Rescue
Promotes composition and modularityPromotes simpler codeConcise, promotes smaller codeConcurrency is not an issueDramatically reduces number of bugs
The Goal of this Presentation
Is not to convince to abandon OOPIs to open your mind for additional paradigmLearn techniques which you can utilize in your favorite programming language
http://theburningmonk.com/2015/04/dont-learn-a-syntax-learn-to-change-the-way-you-think/
A
AAn appetizer:
sorted :: [Integer] -> Boolsorted [] = Truesorted [_] = Truesorted (x:y:zs) = x < y && sorted (y:zs)
So, What Is It All About?Functional Programming Other programming styles
Classes, procedures Building Blocks
N/A A must State changes
Function calls, Loops, conditionals, and function (method) calls
Main control flow
Don’t Panic!!!
FP Principles
ImmutabilityPure functionsModularity and compositionDeclarative
Immutability
Thread safeData flow is explicitCacheable objects
"How many Haskell programmers does it take to change a lightbulb?“ "Haskell
programmers don't "change" lightbulbs, they "replace" them. And you must also
replace the whole house at the same time.”
Idempotence: Get the same results no matter how many times a function is called
We gain the ability to cache results for function calls
Insanity: doing the same thing over and over again and expecting different results.
Albert Einstein
Pure Functions
A function has no side effect We gain clarity We gain “laziness”:
int foo(){
bar();return 0;
}
Pure Functions
Function calls are independentCan be parallelized
result = func1(x,y) + func2(x,z)
Pure Functions
Pure Functions
Encapsulation is in the function levelEasier to debugEasier to test in isolation
Modularity and Composability
A function’s output is only its return valueWe gain:
Modularity with light couplingComposability
Declarative
The focus is on what the computer should do rather than how it should do itThink of a spreadsheet:
We don’t specify the order of calculationsWe don’t deal with variablesWe deal with expressions and not with stepsWe tell it what we want not how to achieve it
Think of SQL…FP is the same but for general purpose
Imperative
List<int> results = new List<int>();foreach(var num in collection){ if (num % 2 != 0) results.Add(num);}
Declarative vs Imperative
Declarativevar results = collection.Where( num => num % 2 != 0);
List<int> collection = new List<int> { 1, 2, 3, 4, 5 };
http://stackoverflow.com/a/1784702/871579
Myths and Misconceptions
It’s difficultIt’s not difficult it’s “just” unfamiliar
We can do it also in XXX (= your favorite language)
Maybe, but “real” FP language is “pushing” you there
It’s not practical for real-world applicationsSimply wrong
FP has poor performanceActually some of the features gives great optimization opportunitiesThe quality code vs optimized code tradeoff
FP is here from the ‘50sAt the beginning computers were slow
Not enough power to process abstractions
Now it’s back!
The Retro of FP
Functional Programming/Language
Functional programming is style of programmingA functional language is one that supports and encourages the functional style
(Some) Functional Language Features
Separate data from behaviorFunctions as First-Class ValuesHigh-Order FunctionsRecursionPattern matchingAlgebraic data types Lazy evaluation
Separate Data from Behavior
No classes and objectsData passes between functions as parameters and return values
Functions as First-Class Values
You can do with functions whatever you can do with other data-types. E.g.:
Bind identifier to a function
Store a function in a data structure
let squareIt = fun n -> n * nlet doubleIt = fun n -> 2 * n
let funList = [ squareIt; doubleIt ]
Functions as First-Class Values
High order functionslet compose = fun op1 op2 -> // Use a let expression to build the function that
will be returned. let funToReturn = fun n -> op1 (op2 n) // Then just return it. funToReturn
let squareAndDouble = compose doubleIt squareIt// The following expression squares 3, doubles 9, returns
18, and // then displays 18.System.Console.WriteLine(squareAndDouble 3)
Recursion
No loops
factorial n = if n < 2 then 1 else n * factorial (n-1)
Pattern Matchingfactorial :: Integer -> Integerfactorial 0 = 1factorial n = n * factorial (n - 1)
fib :: Integer -> Integerfib 0 = 1fib 1 = 1fib n = fib (n-1) + fib (n-2)
length' :: (Num b) => [a] -> b length' [] = 0 length' (_:xs) = 1 + length' xs
Algebraic Data Typesdata Bool = False | True
data Point = Point Float Float deriving (Show) data Shape =
Circle Point Float | Rectangle Point Point deriving (Show)
surface :: Shape -> Float surface (Circle _ r) = pi * r ^ 2 surface (Rectangle (Point x1 y1) (Point x2 y2)) = (abs $
x2 - x1) * (abs $ y2 - y1)
Lazy Evaluation
Evaluation is deferred until their results are neededAllows using infinite listsnats = [0..]
odds = [1,3..]ones = 1 : ones
-- What will happen when executing the following?length oddstake 5 odds
Language ComparisonF# Scala Haskell
CLR (.Net) JVM Native Runtime
Medium1 High (-) High FP Adherence
Default (but may be not)
Default (but may be not)
Yes Immutability
Yes Not by default (but can be)
Yes Lazy Evaluation
Yes Yes Yes Algebraic Data Types
1) E.g. functions are not guaranteed to be pure: let tm = DateTime.Now
Demo
Imperative to FP Evolution
What should you Take?
Don’t learn a syntax, learn to change the way you thinkAdd new paradigms to your toolboxGet out of your comfort zone
Functional Programming is an Opportunity
Questions
Copyright © SELA Software & Education Labs, Ltd. | 14-18 Baruch Hirsch St., Bnei Brak 51202, Israel | www.selagroup.com
Thank You
http://il.linkedin.com/in/eladavneri/
http://blogs.microsoft.co.il/elada
Elad AvneriArchitect, ALM and Software Development