31
Copyright © SELA Software & Education Labs, Ltd. | 14-18 Baruch Hirsch St., Bnei Brak 51202, Israel | www.selagroup.com Functional Programming High Level Introduction [email protected] l http://il.linkedin.com/in/eladavn http:// blogs.microsoft.co.il/el Elad Avneri Architect, ALM and Software Development

Functional pogramming hl overview

Embed Size (px)

Citation preview

Page 1: 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

[email protected]

http://il.linkedin.com/in/eladavneri/

http://blogs.microsoft.co.il/elada

Elad AvneriArchitect, ALM and Software Development

Page 2: Functional pogramming hl overview

Agenda

The BasicsPrinciplesFP Languages

FeaturesComparison

Demo: Imperative to FP Evolution

Page 3: Functional pogramming hl overview

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

Page 4: Functional pogramming hl overview

FP to the Rescue

Promotes composition and modularityPromotes simpler codeConcise, promotes smaller codeConcurrency is not an issueDramatically reduces number of bugs

Page 5: Functional pogramming hl overview

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/

Page 6: Functional pogramming hl overview

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!!!

Page 7: Functional pogramming hl overview

FP Principles

ImmutabilityPure functionsModularity and compositionDeclarative

Page 8: Functional pogramming hl overview

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.”

Page 9: Functional pogramming hl overview

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

Page 10: Functional pogramming hl overview

A function has no side effect We gain clarity We gain “laziness”:

int foo(){

bar();return 0;

}

Pure Functions

Page 11: Functional pogramming hl overview

Function calls are independentCan be parallelized

result = func1(x,y) + func2(x,z)

Pure Functions

Page 12: Functional pogramming hl overview

Pure Functions

Encapsulation is in the function levelEasier to debugEasier to test in isolation

Page 13: Functional pogramming hl overview

Modularity and Composability

A function’s output is only its return valueWe gain:

Modularity with light couplingComposability

Page 14: Functional pogramming hl overview

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

Page 15: Functional pogramming hl overview

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

Page 16: Functional pogramming hl overview

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

Page 17: Functional pogramming hl overview

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

Page 18: Functional pogramming hl overview

Functional Programming/Language

Functional programming is style of programmingA functional language is one that supports and encourages the functional style

Page 19: Functional pogramming hl overview

(Some) Functional Language Features

Separate data from behaviorFunctions as First-Class ValuesHigh-Order FunctionsRecursionPattern matchingAlgebraic data types Lazy evaluation

Page 20: Functional pogramming hl overview

Separate Data from Behavior

No classes and objectsData passes between functions as parameters and return values

Page 21: Functional pogramming hl overview

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 ]

Page 22: Functional pogramming hl overview

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)

Page 23: Functional pogramming hl overview

Recursion

No loops

factorial n = if n < 2 then 1 else n * factorial (n-1)

Page 24: Functional pogramming hl overview

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

Page 25: Functional pogramming hl overview

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)

Page 26: Functional pogramming hl overview

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

Page 27: Functional pogramming hl overview

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

Page 28: Functional pogramming hl overview

Demo

Imperative to FP Evolution

Page 29: Functional pogramming hl overview

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

Page 30: Functional pogramming hl overview

Questions

Page 31: Functional pogramming hl overview

Copyright © SELA Software & Education Labs, Ltd. | 14-18 Baruch Hirsch St., Bnei Brak 51202, Israel | www.selagroup.com

Thank You

[email protected]

http://il.linkedin.com/in/eladavneri/

http://blogs.microsoft.co.il/elada

Elad AvneriArchitect, ALM and Software Development