+ All Categories
Home > Engineering > Functional Programming per tutti

Functional Programming per tutti

Date post: 11-Feb-2017
Category:
Upload: giancarlo-valente
View: 133 times
Download: 2 times
Share this document with a friend
143
FUNCTIONAL PROGRAMMING PER TUTTI di Giancarlo Valente
Transcript

FUNCTIONAL PROGRAMMINGPER TUTTI

di Giancarlo Valente

CHI SONO@gncvalente

agile coachclubauLABhack-ademy

www.giancarlovalente.it - agile coach

Club degli Sviluppatori Puglia

www.aulab.it

www.hack-ademy.it - coding bootcamp

FUNCTIONAL PROGRAMMINGf per full screen

VI E' MAI CAPITATO DURANTE IL LAVORO DI PENSARE ...che tutto e' completamente sbagliatoinutilmente complicato

SI

1996

VB

PYTHON

LIST COMPREHENSIONSpython - list comprehensions

00:00

LIST COMPREHENSIONS - CON FILTROpython - list comprehensions - con �ltro

00:00

LA MIA FANTASIA INIZIO' A CORRERE IN UN PARADISO DI ELEGANZA cartelle_esattoriali = [ elabora_cartella(contribuente) for contribuente in contribuenti if contribuente.valido ]

MENTRE OGNI GIORNO DOVEVO FARE QUESTO Dim contribuenti(100) as Contribuente Dim cartelle_esattoriali As New List(Of Cartella_Esattoriale) Dim i ad Integer For i = 1 To contribuenti.Length contribuente = contribuenti[i] if contribuente.valido then cartelle_esattoriali.add(elabora_cartella(contribuente)) end if Next

il python posso leggerlo

il vb devo eseguirlo

cartelle_esattoriali = [ elabora_cartella(contribuente) for contribuente in contribuenti if contribuente.valido ]

Dim contribuenti(100) as Contribuente Dim cartelle_esattoriali As New List(Of Cartella_Esattoriale) Dim i as Integer For i = 1 To contribuenti.Length contribuente = contribuenti[i] if contribuente.valido then cartelle_esattoriali.add(elabora_cartella(contribuente)) end if Next

wikipedia List Comprehension

IL TEMPO E' PASSATO ...

C# RULEZ!!!... fast forward >> 2006

OOP, Ereditarieta', Plimor�smo, Design Patterns ...

:)

JAVASCRIPT on('ready', function() { var x = "Ciao Mondo"; alert(x); });

PROTOTYPE

SCRIPT.ACULO.US

AGOSTO 2006Can Your Programming Language Do This?

JOEL ON SOFTWARE - Can Your Programming Language Do This?

javascript - funzioni passate come parametro

00:00

JAVASCRIPT E' UN'IMPLEMENTAZIONE DI SCHEME ????"In 1995, the company recruited Brendan Eich with the goal of embedding the Scheme

programming language into its Netscape Navigator. "

wikipedia

FUNCTIONAL PROGRAMMINGFOR THE REST OF US

here

UNA NUOVA SCOPERTAfunctional programming

LA STORIA

1941lambda calculus

Alonzo Church

Church invented a formal system called the lambda calculus

LAMBDA CALCULUSterminivariabilifunction applicationfunction abstraction ( lambda )

LAMBDA CALCULUSfunzioni che accettano altre funzioni come parametro e ritornano funzioni come risultato

LAMBDA CALCULUSnon di parla di "esecuzione"

ma si parla di riduzione

lambda calcolo in js

00:00

fonte - sorgente giuhub

MACCHINA DI TURING

QUALSIASI MACCHINA DI TURING

PUO' ESSERE ESPRESSA IN LAMBDA CALCOLO

Turing machines and lambda calculus are equivalent in power

in 1936 Turing proved that both models are equally strong in the sensethat they de�ne the same class of computable functions

History of Computing at Princeton University

Lambda Calculus ( Declarative )

Alonzo Church

Turing Machine ( Imperative )

Alan Turing

Based on the concept of a Turing machine are the present day Von Neumann computers.Conceptually these are Turing machines with random access registers. Imperative programminglanguages such as Fortran, Pascal etcetera as well as all the assembler languages are based on

the way a Turing machine is instructed: by a sequence of statements.

Functional programming languages, like Miranda, ML etcetera, are based on the lambda calculus.An early (although somewhat hybrid) example of such a language is Lisp. Reduction machines are

speci�cally designed for the execution of these functional languages.

fonte - lambda calcolo cs.kun.nl

1960()((()((()))))

John McCarthy

Lisp Machine - wikipedia

BUSINESSIMPERATIVE ... TUTTI NOI

ACCADEMIAFP ... ACCADEMIA

TEMPI MODERNI

MARZO 2005The Free Lunch Is Over: A Fundamental Turn Toward Concurrency in Software

2007 Joe book on Erlang

2014 - ADOZIONEAZIENDE

Facebook (erlang, haskell)Twitter (scala)WhatsApp (erlang)Amazon (erlang)FourSquare (scala)PayPal (scala)

i.e. haxl

case studies

facebook - open source backend tools

2014 - CONFLUENZA

ha seguito ...

...

Java 8 ... implementa le ... lambda

C#, Ruby, python, php

C++ 11

Functional programming in C++

... CHE COSA E' LA PROGRAMMAZIONE FUNZIONALE?QUALI SONO LE SUE CARATTERISTICHE?

IN PRATICA

FUNZIONI

CHE COSA E' UNA FUNZIONE

funzione - wikipedia

FUNCTIONAL PROGRAMMINGtreats computation as the evaluation

of mathematical functions and avoids changing-state

and mutable data

functional programming - wikipedia

FUNCTIONSfunctions maps inputo to output

INPUT x

FUNCTION f:

OUTPUT f(x)

maps values between a domain and a codomain

Input and outputs values already exists

wikipedia - Function in mathematics

FUNCTIONSf(x) = x + 1

1 ---> 2

6 ---> 7

9 ---> 10

un valore e' qualcosa che non cambia nel tempo

A --> ---> B

Stato --> ---> Stato mutato

FUNCTIONAL COMPOSITION

Function Composition - wikipedia

CALCOLO DELL'AREA DEL CERCHIO

r^2 * pi

CALCOLO DELL'AREA DEL CERCHIO

area_cerchio(r) = moltiplica_per_pi( quadrato( r ) )

area_cerchio in elixir - functional composition

00:00

area_cerchio in PHP - functional composition

00:00

FUNCTIONAL-PHP - FUNCTIONAL COMPOSITION use function Functional\compose; $plus2 = function ($x) { return $x + 2; }; $times4 = function ($x) { return $x * 4; }; $composed = compose($plus2, $times4); $result = array_map($composed, array(1, 2, 5, 8)); var_dump($result); // array(12, 16, 28, 40)

github : functional-php

PATTERN MATCHING

PATTERN MATCHINGerlang - simplest pattern matching

00:00

PATTERN MATCHINGerlang - simple pattern matching

00:00

PATTERN MATCHINGhaskell - pattern matching

00:00

IMMUTABILITA'i valori esistono ... le funzioni li mappano soltanto

lo stato non viene modi�cato, ne' trasformato

una funzione viene valutata e ritorna un nuovo valore

EVALUATION

i dati vengono trattati come immutabili

immagina un mondo dove nessuno puo' rubare o modi�care unqualcosa ...

X = X + 1

Fail!

IMMUTABILITYerlang - immutability

00:00

erlang - immutability

00:00

QUESTO E' UNO SCHERZO

MA ... SI PUO' PROGRAMMAREQUALCOSA DI VERO, DI REALE

INQUESTI LINGUAGGI?

IL MIO FOR DEL C AD ESEMPIO ? for (int i = 0; i < 100; ++i) { /* code */ }

NO LOOPS

CONTEGGIOerlang - no loops

00:00

SOMMA DEGLI ELEMENTI DI UNALISTA

sum :: [Int] -> Int sum [] = 0 sum (x:xs) = x + sum(xs)

haskell - no loops - sum list numbers

00:00

haskell - no loops - sum list numbers - module

00:00

SOMMA DEGLI ELEMENTI DI UNALISTA

-module(somma). -export([sum/1]). sum([]) -> 0; sum([H|T]) -> H + sum(T).

erlang - no loops - sum list numbers - module

00:00

MI SEMBRA LIMITATO, OGNIVOLTA CHE DEVO FARE

QUALCOSA DEVO RIFARE QUESTOCICLO ?

HIGHER ORDER FUNCTIONSfunzioni di ordine superiore

Higher-order function - wikipedia

FUNCTIONS AS FIRST CLASSVALUESfunctions are values!!!

FOLDL

se io ho sum e prod che sommano e moltiplicano tutti gli elementi di una lista posso astrarre

HASKELL - FOLD foldl :: (a -> b -> a) -> b -> [a] -> b foldl f z [] = z foldl f z (x:xs) = foldl f (f z x) xs

haskell - foldl - module

00:00

LE FUNZIONI SONO VALORI ...... E VENGONO TRATTATI COME VALORI

CURRYfunctions are values!!!

sum :: [Int] -> Int sum = foldl (+) 0 prod :: [Int] -> Int prod = foldl (*) 1

haskell - foldl - curry

00:00

CURRYApplicazione parziale di una funzione, mi ritorna una funzione che accetta i parametri restanti

come farestin un ciclo di elaborazione in PHP ?

nooooo posso fare di meglio

risultati = [] for elemento in contenitore risultati[] = elabora(elemento)

MAP - PHP STANDARD $stringArray = [ 'prova', 'test', 'ciao']; $result = array_map('strtoupper', $stringArray);

MAP - JS var numbers = [1, 5, 10, 15]; var roots = numbers.map(function(x){ return x * 2; });

MAPfunzione di base di tutti i linguaggi FP

ovviamente esiste l'implementazione di "libreria" ma vediamo come verrebbe implementata in FP

FILTER - PHP $result = array_filter($intArray, function($a) { return ($a % 2 === 0); });

FILTER - ERLANG filter(Pred, L) -> lists:reverse(filter(Pred, L,[])). filter(_, [], Acc) -> Acc; filter(Pred, [H|T], Acc) -> case Pred(H) of true -> filter(Pred, T, [H|Acc]); false -> filter(Pred, T, Acc) end.

LIST COMPREHENSIONS

list comprehensions - wikipedia

map e �lter

erlang - list comprehensions

00:00

MAP, REDUCE, FILTER ETC ETCoggi esistono diverse librerie per ogni linguaggio che facilitano l'adozione di uno stile di

programmaizone funzionale

JS, PHP, C#, C++

CSHARP... LINQ !!!

OOP SOLID PRINCIPLESSingle Responsability PrincipleOpen/closed PrincipleLiskov Substitution PrincipleInterface Segregation Principle

OOP SOLID PRINCIPLESSingle Responsability Principle FunctionOpen/closed Principle higher-order functionsLiskov Substitution Principle polimor�smo parametricoInterface Segregation Principle Function

Lev Gorodinski

DEPENDENCY INJECTIONFunctions passed around !!!

OOP DESIGN PATTERNSFactory FunctionCommand functionStrategy functiondecorator function

Robert C. Martin

REFERENCIAL TRANSPARENCY

f(x,y) = x + y

qualsiasi cosa avvenga all'esterno

dara' sempre lo stesso risultato

BLACK BOX E TESTING

A --> ---> B

UNIT TESTINGno side effectsTesting ... easyfunctions are idempotentalways testing one thing

DEBUGGINGdebugging is easy!

MEMOIZATIONWikipedia

FATTORIALE function factorial($n) { if($n == 1) return 1; return $n * factorial($n - 1); }

FATTORIALE CON MEMOIZATIONin programmazione imperativa

function factorial($n) { static $cache = array(); if($n == 1) return 1; if(! array_key_exists($n, $cache)) { $cache[$n] = $n * factorial($n - 1); } return $cache[$n]; }

FATTORIALE CON MEMOIZATIONin programmazione funzionale

// functional abstraction function memoize($func) { return function() use($func) { static $cache = array(); $args = func_get_args(); $key = serialize($args); if(! array_key_exists($key, $cache)) { $cache[$key] = call_user_func_array($func, $args); } return $cache[$key]; }; }

FATTORIALE CON MEMOIZATIONin programmazione funzionale

// functional programming $factorial = function($n) use(&$factorial) { if($n == 1) return 1; return $n * $factorial($n -1); }; $mem_factorial = memoize($factorial); echo $mem_factorial(10); echo $mem_factorial(10); echo $mem_factorial(11);

php - factorial memoization in FP

00:00

CONCURRENCYno locksno deadlocks

MASSIVELY PARALLELIZABLE

il compilatore puo' analizzare il codice e capire che R1 e R3 possono essere calcolati in parallelo,poi calcola R2, e quindi R4 e' pronto

R1 = faiQualcosa_1_QuiCon(A, B, C) R2 = faiQualcosa_2_QuiCon(A, R1) R3 = faiQualcosa_3_QuiCon(C, D) R4 = faiQualcosa_4_QuiCon(R3, R2) print R4

SEPARATION OF DATA ANDBEHAVIOUR

TREAT CODE AS DATAship executionlisp macros

HOT CODE UPDATEimpossibile in imperative code !

LAZY EVALUATION E STRUTTUREDATI INFINITE

lazy --> enorme potenziale per l'ottimizzazionelazy --> strutture dati in�nite

haskell - in�nite data structures

00:00

haskell - fattoriale con in�nite data structures

00:00

stack-over�ow - In�nitely lazy factorial in Haskell

CAN PROGRAMMING BELIBERATED ...

CAN PROGRAMMING BELIBERATED FROM THE VON

NEUMAN STYLE? A FUNCTIONALSTYLE ...

CAN PROGRAMMING BE LIBERATED FROM THE VON NEUMAN STYLE? AFUNCTIONAL STYLE AND ITS ALGEBRA OF PROGRAMS

John Backus - 1977 Turing Award Lecture

Algebra of programs

IL PRESENTEErlang

IL FUTUROhaskell

Dichiarativo

- per parallelizzare - ottimizzare con le statistiche - definire altrilinguaggi

DICHIARIATIVOHASKELL TROVERA' MAI LA SUA NICCHIA ?

haskell dichiarativo ..

non ci hanno lavorato tante persone quante sul compilatore C

potra' fare come SQL ottimizzazioni anche basandosi sullestatistiche in esecuzione

https://www.quora.com/Is-Haskell-as-fast-as-C++-If-not-why-not

http://elm-lang.org/

Microsoft

http://blog.raintown.org/p/lava.html

FPGA sysntesys from a functional declartive language

http://www.clash-lang.org/http://yager.io/HaSKI/HaSKI.htmlhttp://christiaanb.github.io/posts/clash-fpga-starter/


Recommended