SlideShare a Scribd company logo
PHP funcional
além do
array_map
Jean Carlo Machado
Sobre
CompuFácil
⇢ php-src
⇢ git/git
⇢ torvald/linux
⇢ vim/vim
⇢ Doctrine
⇢ Zend Framework
⇢ phpunit
Haskell
1936: Imperativo
jumps: GOTO
1950: Estruturado
subrotinas: while, for, if
GOTO
Programação
Funcional
mudança de estado
Vantagens
Concorrência nativa
Facilita a modularização
Desacelera o apodrecimento
Functional php
Prática
Estado === Impureza
$inpureIncrement = function (&$count) {
$count++;
};
for ($i = 0; $i < 3; $i++) {
echo "Next:".$inpureIncrement($i);
}
//Next: 0
//Next: 2
//Next: 4
Pureza (relativa)
function pureIncrement($count) {
$myCounter = $count;
$inpureIncrement = function(&$myCounter){
$myCounter++;
};
$inpureIncrement($myCounter);
return $myCounter;
}
//Next: 1
//Next: 2
//Next: 3
Impuros por
natureza
IO
random
Funções de
alta ordem
Retornáveis
$sumPartial = function(int $a) {
return function(int $b) use ($a) {
return $a+b;
}
};
$sumOne = $sumPartial(1);
$sumOne(7);
//8
$sumOne(5);
//6
Repassáveis
$incrementTwo = function ($n, $sumOne) {
return $sumOne($sumOne($n));
};
Fold
Defina o básico
function sum($a, $b) {
return $a + $b;
}
//function product($a, $b);
//function aORb($a, $b);
//function append($a, $b);
//function greater($a, $b);
Componha
$sumList = fold('sum', 0, [1,2,3]);
//6
$multiplyList = fold('product', 1, [2,2,2]);
//8
function fold(
callable $f,
$init,
$list) {
if (empty($list)) {
return $init;
}
return $f(
fold($f, $init, allbutlast($list)),
last($list)
);
};
Map
$double = function($a) {
return $a*2;
}
$map($double, [1, 2, 4]));
//[2,4,8]
$map = function($f, $list) {
$applyAndAppend=function($f,$list,$b){
$list[] = $f($b);
return $list;
};
return fold($applyAndAppend,null)($list);
}
Árvores
$tree = [
1 => [
2,
3 => [
4,
],
]
];
foldTree($sum, $sum, 0, $tree)
//10
Map Tree
$tree = [
3 => [1,4],
1 => [1,5 => [1,2,3]]
];
$result = mapTree($double, $tree);
//[
// 6 => [2,8],
// 2 => [2,10 => [2,4,6]]
//];
PHP functions
⇢ array_map
⇢ array_filter
⇢ array_reduce
⇢ array_sum
⇢ array_unique
g (f input)
⇢ começa f só quando g tenta ler algo
⇢ suspende f
⇢ g roda até precisar ler mais dados
Nth primes
getNthPrimes(10);
//[1,2,3,5,7,11,13,17,19,23]
Nth primes
function primes() {
foreach (finfiniteSequence(1) as $i) {
if (isPrime($i)) {
yield $i;
}
}
}
print_r(ftakefrom(primes(), 10));
//[1,2,3,5,7,11,13,17,19,23]
function isPrime($x) {
$seq = ftakeFrom(
finfiniteSequence(),
$x
);
$seq = fremoveFirst($seq);
$seq = fremoveLast($seq);
$multiple = function($a) use ($x) {
return ($x % $a == 0);
}
return fnoneTrue(
fmap($multiple, $seq)
);
Aplicação parcial
$append3 = function($a, $b, $c) {
return [$a, $b, $c];
};
$append1And2 = fpartial($append3)(1)(2);
$append1And2(5)
//[1,2,5]
$append1And2(9)
//[1,2,9]
function partial(
callable $callable, ...$args){
$arity = (new ReflectionFunction(
$callable
))
->getNumberOfRequiredParameters();
return $args[$arity - 1] ?? false
? $callable(...$args)
: function (...$passedArgs)use($callable,
return partial($callable,
...array_merge($args, $passedArgs)
);
};
Real: get-profile
Requisito v1
curl http://localhost:8000/profile/777
#{"id":777,"name":"Saruman"}
function getProfile(
callable $query,
$userId) {
return $query(
"Select * from User where id = %id ",
$userId
);
}
$realProfile = fpartial
('getProfile')
([new Database, 'query']);
Requisito v2:
cache
curl http://localhost:8000/profile/777
# go to database
#{"id":777,"name":"Saruman"}
curl http://localhost:8000/profile/777
# don't go to database
#{"id":777,"name":"Saruman"}
$memoize = function($func) {
static $results = [];
return function ($a) use (
$func, &$results) {
$key = serialize($a);
if (empty($results[$key])){
$results[$key]=call_user_func(
$func, $a );
}
return $results[$key];
};};
$memoizedProfile = $memoize($realProfile);
Requisito v3: log
request
curl http://localhost:8000/profile/777
#{"id":777,"name":"Saruman"}
# also writes to file
cat /tmp/log
#getProfile called with params s:3:"777";
function fileLogger($str) {
file_put_contents(
'/tmp/log',
"FileLog: ".$str.PHP_EOL,
FILE_APPEND
);
}
function logService(
$logger, $serviceName,
callable $service) {
return function($args) use (
$logger, $serviceName,
$service) {
$logger(
"Service called ". $serviceName.
" with params ".serialize($args));
return call_user_func($service, $args);
};
};
$loggedMemoizedGetProfile =
fpartial('logService')
($logger)
('getProfile')
($memoizedProfile);
Modularização
Mais que módulos
Decompor os problemas em partes menores
Re-compor com avaliação tardia e funções de alta
ordem
Apodrecimento
⇢ Difícil adicionar efeitos sem quebrar as interfaces
⇢ Quão maior a interface mais feio o código
⇢ Interfaces facilmente quebráveis com composicão
⇢ Quebrar encoraja reúso
⇢ Complexidade horizontal ao invés de vertical
Conclusão
Imperativo quando necessário
Funcional quando possível
Para novos tipos
1 - defina as operações fundamentais
2 - junte funções
Seu trabalho não é resolver problemas
Definir problemas de uma forma que
eles se resolvam
Ferramentas
⇢ hlstrojny/functional-php
⇢ functional-php/pattern-matching
⇢ jeanCarloMachado/f
⇢ pimple/pimple
Referências
⇢ Why functional programming matters
⇢ http://archive.li/uTYWZ#selection-407.912-407.919
⇢ https://medium.com/@jugoncalves/functional-programming-
should-be-your-1-priority-for-2015-47dd4641d6b9
⇢ https://blog.inf.ed.ac.uk/sapm/2014/03/06/enemy-of-the-
state-or-why-oop-is-not-suited-to-large-scale-software/
⇢ https://www.youtube.com/watch?v=7Zlp9rKHGD4
⇢ https://www.youtube.com/watch?v=q0HRCEKAcas
Dúvidas?
Github: https://github.com/jeanCarloMachado
Twitter: https://twitter.com/JeanCarloMachad
E-mail: contato@jeancarlomachado.com.br

More Related Content

PDF
Git avançado
PDF
Meet up symfony 16 juin 2017 - Les PSR
PDF
Perl6 operators and metaoperators
PDF
Advanced modulinos
PDF
Bag of tricks
DOC
basic shell_programs
PDF
Darkmira Tour PHP 2016 - Automatizando Tarefas com Phing
PDF
Perl Bag of Tricks - Baltimore Perl mongers
Git avançado
Meet up symfony 16 juin 2017 - Les PSR
Perl6 operators and metaoperators
Advanced modulinos
Bag of tricks
basic shell_programs
Darkmira Tour PHP 2016 - Automatizando Tarefas com Phing
Perl Bag of Tricks - Baltimore Perl mongers

What's hot (20)

PDF
20 modules i haven't yet talked about
DOCX
PDF
Parsing JSON with a single regex
PDF
How to stand on the shoulders of giants
PDF
C++ programs
ODP
PHP pod mikroskopom
PDF
ZeroMQ Is The Answer: DPC 11 Version
DOCX
C program to implement linked list using array abstract data type
DOCX
Pratik Bakane C++
DOCX
Pratik Bakane C++
PDF
Decoupling Objects With Standard Interfaces
PDF
The Magic Of Tie
DOC
The Truth About Lambdas in PHP
DOC
Final ds record
DOCX
Pratik Bakane C++
DOCX
Pratik Bakane C++
DOCX
Pratik Bakane C++
PDF
2016 gunma.web games-and-asm.js
DOCX
Circular queue
20 modules i haven't yet talked about
Parsing JSON with a single regex
How to stand on the shoulders of giants
C++ programs
PHP pod mikroskopom
ZeroMQ Is The Answer: DPC 11 Version
C program to implement linked list using array abstract data type
Pratik Bakane C++
Pratik Bakane C++
Decoupling Objects With Standard Interfaces
The Magic Of Tie
The Truth About Lambdas in PHP
Final ds record
Pratik Bakane C++
Pratik Bakane C++
Pratik Bakane C++
2016 gunma.web games-and-asm.js
Circular queue
Ad

Similar to Functional php (20)

PDF
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PDF
Functional programming with php7
PDF
Functional Programming in PHP
PPTX
Adding Dependency Injection to Legacy Applications
PDF
エラー時にログに出力する情報と画面に表示する情報を分ける #LaravelTokyo
PDF
Object Oriented Programming with PHP 5 - More OOP
PDF
Why async and functional programming in PHP7 suck and how to get overr it?
PDF
Generating Power with Yield
KEY
Can't Miss Features of PHP 5.3 and 5.4
PDF
Functional Structures in PHP
PDF
JavaScript for PHP developers
PDF
jQuery: out with the old, in with the new
PDF
Elements of Functional Programming in PHP
PPTX
Tidy Up Your Code
PDF
Unittests für Dummies
PPTX
A Functional Guide to Cat Herding with PHP Generators
ODP
The promise of asynchronous php
PDF
Durian: a PHP 5.5 microframework with generator-style middleware
PDF
SPL: The Missing Link in Development
DOC
Jsphp 110312161301-phpapp02
PHPCon 2016: PHP7 by Witek Adamus / XSolve
Functional programming with php7
Functional Programming in PHP
Adding Dependency Injection to Legacy Applications
エラー時にログに出力する情報と画面に表示する情報を分ける #LaravelTokyo
Object Oriented Programming with PHP 5 - More OOP
Why async and functional programming in PHP7 suck and how to get overr it?
Generating Power with Yield
Can't Miss Features of PHP 5.3 and 5.4
Functional Structures in PHP
JavaScript for PHP developers
jQuery: out with the old, in with the new
Elements of Functional Programming in PHP
Tidy Up Your Code
Unittests für Dummies
A Functional Guide to Cat Herding with PHP Generators
The promise of asynchronous php
Durian: a PHP 5.5 microframework with generator-style middleware
SPL: The Missing Link in Development
Jsphp 110312161301-phpapp02
Ad

More from Jean Carlo Machado (10)

PDF
Python clean code for data producs
PDF
Domain Driven Design Made Functional with Python
PDF
Search microservice
PDF
Why functional programming matters
PDF
Clean code v3
PDF
Clean Code V2
PDF
Review articles bio inspired algorithms
PDF
Introduction to Rust
ODP
Limitações do HTML no Desenvolvimento de Jogos Multiplataforma
PDF
Clean code
Python clean code for data producs
Domain Driven Design Made Functional with Python
Search microservice
Why functional programming matters
Clean code v3
Clean Code V2
Review articles bio inspired algorithms
Introduction to Rust
Limitações do HTML no Desenvolvimento de Jogos Multiplataforma
Clean code

Recently uploaded (20)

PPTX
Why Generative AI is the Future of Content, Code & Creativity?
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Digital Strategies for Manufacturing Companies
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
iTop VPN Free 5.6.0.5262 Crack latest version 2025
PDF
Nekopoi APK 2025 free lastest update
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Understanding Forklifts - TECH EHS Solution
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
Cost to Outsource Software Development in 2025
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
assetexplorer- product-overview - presentation
PPTX
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
Why Generative AI is the Future of Content, Code & Creativity?
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Softaken Excel to vCard Converter Software.pdf
Digital Strategies for Manufacturing Companies
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
iTop VPN Free 5.6.0.5262 Crack latest version 2025
Nekopoi APK 2025 free lastest update
CHAPTER 2 - PM Management and IT Context
Understanding Forklifts - TECH EHS Solution
How to Choose the Right IT Partner for Your Business in Malaysia
Reimagine Home Health with the Power of Agentic AI​
Cost to Outsource Software Development in 2025
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Which alternative to Crystal Reports is best for small or large businesses.pdf
assetexplorer- product-overview - presentation
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
wealthsignaloriginal-com-DS-text-... (1).pdf

Functional php