FUNCTIONAL PROGRAMMING
PER TUTTI
di Giancarlo Valente
CHI SONO
@gncvalente
agile coach
club
auLAB
hack-ademy
www.giancarlovalente.it - agile coach
Club degli Sviluppatori Puglia
www.aulab.it
www.hack-ademy.it - coding bootcamp
FUNCTIONAL PROGRAMMING
f per full screen
VI E' MAI CAPITATO DURANTE IL LAVORO DI PENSARE ...
che tutto e' completamente sbagliato
inutilmente complicato
SI
1996
VB
PYTHON
LIST COMPREHENSIONS
python - list comprehensions
00:00
LIST COMPREHENSIONS - CON FILTRO
python - 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
Thomas Fuchs
AGOSTO 2006
Can 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 PROGRAMMING
FOR THE REST OF US
here
UNA NUOVA SCOPERTA
functional programming
LA STORIA
1941
lambda calculus
Alonzo Church
Church invented a formal system called the lambda calculus
LAMBDA CALCULUS
termini
variabili
function application
function abstraction ( lambda )
LAMBDA CALCULUS
funzioni che accettano altre funzioni come parametro e ritornano funzioni come risultato
LAMBDA CALCULUS
non 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 sense
that 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 programming
languages 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
BUSINESS
IMPERATIVE ... TUTTI NOI
ACCADEMIA
FP ... ACCADEMIA
TEMPI MODERNI
MARZO 2005
The Free Lunch Is Over: A Fundamental Turn Toward Concurrency in Software
www.adapteva.com
Epiphany-V: A 1024-core 64-bit RISC processor
2007
Joe book on Erlang
2014 - ADOZIONE
AZIENDE
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 PROGRAMMING
treats computation as the evaluation
of mathematical functions
and avoids changing-state
and mutable data
functional programming - wikipedia
FUNCTIONS
functions 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
FUNCTIONS
f(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 js
00:00
area_cerchio in elixir - functional composition
00:00
area_cerchio in PHP - functional composition
00:00
FUNCTIONAL-PHP - FUNCTIONAL COMPOSITION
use function Functionalcompose;
$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 MATCHING
erlang - simplest pattern matching
00:00
PATTERN MATCHING
erlang - simple pattern matching
00:00
PATTERN MATCHING
haskell - 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 un
qualcosa ...
X = X + 1
Fail!
IMMUTABILITY
erlang - immutability
00:00
erlang - immutability
00:00
QUESTO E' UNO SCHERZO
MA ... SI PUO' PROGRAMMARE
QUALCOSA DI VERO, DI REALE
INQUESTI LINGUAGGI?
IL MIO FOR DEL C AD ESEMPIO ?
for (int i = 0; i < 100; ++i)
{
/* code */
}
NO LOOPS
CONTEGGIO
erlang - no loops
00:00
SOMMA DEGLI ELEMENTI DI UNA
LISTA
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 UNA
LISTA
-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, OGNI
VOLTA CHE DEVO FARE
QUALCOSA DEVO RIFARE QUESTO
CICLO ?
HIGHER ORDER FUNCTIONS
funzioni di ordine superiore
Higher-order function - wikipedia
FUNCTIONS AS FIRST CLASS
VALUES
functions are values!!!
FOLDL
se io ho sum e prod che sommano e moltiplicano tutti gli elementi di una lista posso astrarre
erlang - foldl
00:00
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
CURRY
functions are values!!!
sum :: [Int] -> Int
sum = foldl (+) 0
prod :: [Int] -> Int
prod = foldl (*) 1
haskell - foldl - curry
00:00
CURRY
Applicazione 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;
});
MAP
funzione di base di tutti i linguaggi FP
ovviamente esiste l'implementazione di "libreria" ma vediamo come verrebbe implementata in FP
haskell - map
00:00
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 ETC
oggi esistono diverse librerie per ogni linguaggio che facilitano l'adozione di uno stile di
programmaizone funzionale
JS, PHP, C#, C++
JS
lo dash
lazy js
ramda
PHP
functional php
phunctional
CSHARP
... LINQ !!!
OOP SOLID PRINCIPLES
Single Responsability Principle
Open/closed Principle
Liskov Substitution Principle
Interface Segregation Principle
OOP SOLID PRINCIPLES
Single Responsability Principle Function
Open/closed Principle higher-order functions
Liskov Substitution Principle polimor smo parametrico
Interface Segregation Principle Function
Lev Gorodinski
DEPENDENCY INJECTION
Functions passed around !!!
OOP DESIGN PATTERNS
Factory Function
Command function
Strategy function
decorator 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 TESTING
no side effects
Testing ... easy
functions are idempotent
always testing one thing
DEBUGGING
debugging is easy!
MEMOIZATION
Wikipedia
FATTORIALE
function factorial($n) {
if($n == 1) return 1;
return $n * factorial($n - 1);
}
FATTORIALE CON MEMOIZATION
in 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 MEMOIZATION
in 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 MEMOIZATION
in 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
CONCURRENCY
no locks
no 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 AND
BEHAVIOUR
TREAT CODE AS DATA
ship execution
lisp macros
HOT CODE UPDATE
impossibile in imperative code !
LAZY EVALUATION E STRUTTURE
DATI INFINITE
lazy --> enorme potenziale per l'ottimizzazione
lazy --> 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 BE
LIBERATED ...
CAN PROGRAMMING BE
LIBERATED FROM THE VON
NEUMAN STYLE? A FUNCTIONAL
STYLE ...
CAN PROGRAMMING BE LIBERATED FROM THE VON NEUMAN STYLE? A
FUNCTIONAL STYLE AND ITS ALGEBRA OF PROGRAMS
John Backus - 1977 Turing Award Lecture
Algebra of programs
IL PRESENTE
Erlang
IL FUTURO
haskell
Dichiarativo
- per parallelizzare
- ottimizzare con le statistiche
- definire altrilinguaggi
DICHIARIATIVO
HASKELL 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.html
http://christiaanb.github.io/posts/clash-fpga-starter/

Functional Programming per tutti