why async and functional programming in php7 suck and how to get overr it?

141
Witek Adamus DocPlanner 2017, Warszawa

Upload: witek-adamus

Post on 21-Feb-2017

54 views

Category:

Engineering


2 download

TRANSCRIPT

Page 1: Why async and functional programming in PHP7 suck and how to get overr it?

Witek Adamus

DocPlanner 2017, Warszawa

Page 2: Why async and functional programming in PHP7 suck and how to get overr it?

Why async and functional programming in PHP7 suck and how to get over it?

Page 3: Why async and functional programming in PHP7 suck and how to get overr it?

Who am I?

Page 4: Why async and functional programming in PHP7 suck and how to get overr it?

5 years of

imperative

programming

2 years of

functional

programming

Back to

PHP7

Page 5: Why async and functional programming in PHP7 suck and how to get overr it?

❏ WHY?❏ What can functional programming bring to the table?

❏ WHAT?❏ When language can be described as functional?

❏ PROBLEMS?❏ Top sins of PHP

❏ SOLUTION?

Table of content

Page 6: Why async and functional programming in PHP7 suck and how to get overr it?

WHY?

Page 7: Why async and functional programming in PHP7 suck and how to get overr it?

❏ Higher quality?❏ Speed / Scalability❏ Less bugs❏ Easy to reason about❏ Predictability

WHY?

Page 8: Why async and functional programming in PHP7 suck and how to get overr it?

WHY?

Pros Cons

Efficiency ???

Entry threshold ???

Mathematical description of

reality

???

Page 9: Why async and functional programming in PHP7 suck and how to get overr it?

WHY?

Pros Cons In result

Efficiency Efficiency Scalability / Quality

Entry threshold Entry threshold Let’s get the party started

Mathematical description of

reality

Mathematical description of

reality

Shorter and more descriptive code

Page 10: Why async and functional programming in PHP7 suck and how to get overr it?

WHY?

Pros Cons In result

Efficiency Efficiency Scalability / Quality

Entry threshold Entry threshold Let’s get the party started

Mathematical description of

reality

Mathematical description of

reality

Shorter and more descriptive code

INVEST AND WAITFOR A DIVIDEND

Page 11: Why async and functional programming in PHP7 suck and how to get overr it?

public function someMethodWithMisleadingName( array $mysteriousInput){ $arr = []; foreach ($mysteriousInput as $inp) { if ($inp > 10) { $arr[] = $inp; } } $arrLeft = $arrRight = $arrCenter = []; foreach ($arr as $elem) { $bucket = $elem <=> 20; if ($bucket < 0) { $arrLeft[] = $elem; } if ($bucket == 0) { $arrCenter[] = $elem; } if ($bucket > 0) { $arrRight[] = $elem;} } $countLeft = count($arrLeft); $countCenter = count($arrCenter); $countRight = count($arrRight); return array_sum([$countLeft, $countCenter, $countRight]) / 3;}

Page 12: Why async and functional programming in PHP7 suck and how to get overr it?

public function someMethodWithMisleadingName( array $mysteriousInput) { $arr = []; foreach ($mysteriousInput as $inp) { if ($inp > 10) { $arr[] = $inp; } } $arrLeft = $arrRight = $arrCenter = []; foreach ($arr as $elem) { $bucket = $elem <=> 20; if ($bucket < 0) { $arrLeft[] = $elem; } if ($bucket == 0) { $arrCenter[] = $elem; } if ($bucket > 0) { $arrRight[] = $elem;} } $countLeft = count($arrLeft); $countCenter = count($arrCenter); $countRight = count($arrRight); return array_sum(

[$countLeft, $countCenter, $countRight]) / 3;

}

public function someMethodWithMisleadingName( ParallelListCollection $mysteriousInput) { return $mysteriousInput

->filter(function ($elem) {return $elem > 10;

})->partition(function ($elem) {

return $elem <=> 20;})->map(function ($bucket) {

return $bucket->count();})->avg();

}

Page 13: Why async and functional programming in PHP7 suck and how to get overr it?

public function someMethodWithMisleadingName( array $mysteriousInput) { $arr = []; foreach ($mysteriousInput as $inp) { if ($inp > 10) { $arr[] = $inp; } } $arrLeft = $arrRight = $arrCenter = []; foreach ($arr as $elem) { $bucket = $elem <=> 20; if ($bucket < 0) { $arrLeft[] = $elem; } if ($bucket == 0) { $arrCenter[] = $elem; } if ($bucket > 0) { $arrRight[] = $elem;} } $countLeft = count($arrLeft); $countCenter = count($arrCenter); $countRight = count($arrRight); return array_sum(

[$countLeft, $countCenter, $countRight]) / 3;

}

public function someMethodWithMisleadingName( ParallelListCollection $mysteriousInput) { return $mysteriousInput

->filter(function ($elem) {return $elem > 10;

})->partition(function ($elem) {

return $elem <=> 20;})->map(function ($bucket) {

return $bucket->count();})->avg();

}

Page 14: Why async and functional programming in PHP7 suck and how to get overr it?

WHAT?

❏ Function is a first-class citizen

❏ Lambda Calculus

❏ Immutability

❏ No side effects

Page 15: Why async and functional programming in PHP7 suck and how to get overr it?

First-class citizen

❏ Can be stored in variable and data structures

❏ Can be passed as a parameter to procedure/functions

❏ Can be returned by procedures/functions

❏ Can be instantiated inline

❏ Has it’s own identity (name independent)

Page 16: Why async and functional programming in PHP7 suck and how to get overr it?

Lambda Calculus

ƛ(x) = z

Page 17: Why async and functional programming in PHP7 suck and how to get overr it?

Lambda Calculus

ƛ(x) = z❏ Higher-order functions❏ Currying

Page 18: Why async and functional programming in PHP7 suck and how to get overr it?

Lambda Calculus

ƛ(x) = z❏ Higher-order functions❏ Currying

SWITCH YOUR THINKING

FROM “HOW?” TO “WHAT?”

Page 19: Why async and functional programming in PHP7 suck and how to get overr it?

No side effects? Immutability?

:(

Page 20: Why async and functional programming in PHP7 suck and how to get overr it?

Functional vs Object oriented programming

?

Page 21: Why async and functional programming in PHP7 suck and how to get overr it?
Page 22: Why async and functional programming in PHP7 suck and how to get overr it?

PHP7 is functional

…but is dirty and salty as well

Page 23: Why async and functional programming in PHP7 suck and how to get overr it?

What do I miss in PHP7 that Scala luckily has?

Page 24: Why async and functional programming in PHP7 suck and how to get overr it?

❏ Immutability by default❏ Objects cloning❏ Options❏ Either❏ Future❏ Parallel collections❏ Tail recurrency

❏ Generic types❏ Arrow functions❏ Pattern matching / case classes

Page 25: Why async and functional programming in PHP7 suck and how to get overr it?

https://github.com/php-slang/php-slang

http://phpslang.io

# composer require php-slang/php-slang

Page 26: Why async and functional programming in PHP7 suck and how to get overr it?

Few rules to make your code functional

Page 27: Why async and functional programming in PHP7 suck and how to get overr it?

Do not use

❏ reassignments❏ if❏ null❏ for❏ foreach

Page 28: Why async and functional programming in PHP7 suck and how to get overr it?

Quick pool

❏ Do you DDD?

Page 29: Why async and functional programming in PHP7 suck and how to get overr it?

Quick pool

❏ Do you DDD?❏ Do you use setters?

Page 30: Why async and functional programming in PHP7 suck and how to get overr it?

Quick pool

❏ Do you DDD?❏ Do you use setters?

“VALUE OBJECTS are completely immutable.”Eric Evans

Page 31: Why async and functional programming in PHP7 suck and how to get overr it?

Do not use

❏ reassignments

Page 32: Why async and functional programming in PHP7 suck and how to get overr it?

$bigHouse = new Building(5);

Page 33: Why async and functional programming in PHP7 suck and how to get overr it?

$bigHouse = new Building(5);$smallerHouse = $bigHouse->setFloors(2);

echo $bigHouse->getFloors(); echo $smallerHouse->getFloors();

Page 34: Why async and functional programming in PHP7 suck and how to get overr it?

$bigHouse = new Building(5);$smallerHouse = $bigHouse->setFloors(2);

echo $bigHouse->getFloors(); //2echo $smallerHouse->getFloors(); //2

Page 35: Why async and functional programming in PHP7 suck and how to get overr it?

class Building{ protected $floors;

public function __construct(int $floors) { $this->setFloors($floors); }

public function getFloors() : int { return $this->floors; }

public function setFloors(int $floors) : Building { $this->floors = $floors; return $this; }}

Page 36: Why async and functional programming in PHP7 suck and how to get overr it?

use PhpSlang\Util\Copy;

class Building{ use Copy;

protected $floors;

public function __construct(int $floors) { $this->floors = $floors; }

public function getFloors() : int { return $this->floors; }

public function withFloors(int $floors) : Building { return $this->copy('floors', $floors); }}

Page 37: Why async and functional programming in PHP7 suck and how to get overr it?

$bigHouse = new Building(5);$smallerHouse = $bigHouse->withFloors(2);

echo $bigHouse->getFloors(); //5echo $smallerHouse->getFloors(); //2

Page 38: Why async and functional programming in PHP7 suck and how to get overr it?

$bigHouse = new Building(5);$smallerHouse = $bigHouse->withFloors(2);

echo $bigHouse->getFloors(); //5echo $smallerHouse->getFloors(); //2

REFERENTIAL TRANSPARENCY

Page 39: Why async and functional programming in PHP7 suck and how to get overr it?

Referential transparency

❏ f(x, y) = (x+y) * y

Page 40: Why async and functional programming in PHP7 suck and how to get overr it?

Referential transparency

❏ f(x, y) = (x+y) * y

x, y and a result can be a function as well

Page 41: Why async and functional programming in PHP7 suck and how to get overr it?

Referential transparency

❏ f(x, y) = (x+y) * y

Eg.

❏ f(2, 4) = (2 + 4) * 4 = 8 * 4 = 32

❏ f(1, 8) = (1 + 8) * 8 = 9 * 8 = 72

Page 42: Why async and functional programming in PHP7 suck and how to get overr it?

Referential transparency

❏ f(x, y) = (x+y) * y

Eg.

❏ f(2, 4) = (2 + 4) * 4 = 8 * 4 = 32

❏ f(1, 8) = (1 + 8) * 8 = 9 * 8 = 72

i = 71;ComputingService::_opCount++;comps.push(new Tuple2(x, y));

Page 43: Why async and functional programming in PHP7 suck and how to get overr it?

Referential transparency

❏ f(x, y) = (x+y) * y

Eg.

❏ f(2, 4) = (2 + 4) * 4 = 8 * 4 = 32

❏ f(1, 8) = (1 + 8) * 8 = 9 * 8 = 72

i = 71;ComputingService::_opCount++;comps.push(new Tuple2(x, y));

Page 44: Why async and functional programming in PHP7 suck and how to get overr it?

Few rules to make your code functional

Page 45: Why async and functional programming in PHP7 suck and how to get overr it?

Do not use

:) reassignments❏ if❏ null❏ for❏ foreach

Page 46: Why async and functional programming in PHP7 suck and how to get overr it?

Do not use

:) reassignments❏ if❏ null❏ for❏ foreach

?

Page 47: Why async and functional programming in PHP7 suck and how to get overr it?

Do not use

:) reassignments❏ if❏ null❏ for❏ foreach

Option

Page 48: Why async and functional programming in PHP7 suck and how to get overr it?

OptionMonad which may contain something or nothing

Page 49: Why async and functional programming in PHP7 suck and how to get overr it?

What is a monad?

Page 50: Why async and functional programming in PHP7 suck and how to get overr it?

What is a monad?

Page 51: Why async and functional programming in PHP7 suck and how to get overr it?

What is a monad?

Page 52: Why async and functional programming in PHP7 suck and how to get overr it?

What is a monad?

Page 53: Why async and functional programming in PHP7 suck and how to get overr it?

What is a monad?

map

Page 54: Why async and functional programming in PHP7 suck and how to get overr it?

What is a monad?

flatMap

Page 55: Why async and functional programming in PHP7 suck and how to get overr it?

What is a monad?

Page 56: Why async and functional programming in PHP7 suck and how to get overr it?

Option

Option

NoneSome

Page 57: Why async and functional programming in PHP7 suck and how to get overr it?

Option

Option

NoneSomemap(Closure $expression)getOrElse($default)

map(Closure $expression)getOrElse($default)

Page 58: Why async and functional programming in PHP7 suck and how to get overr it?

Option

Option

NoneSomemap(Closure $expression)getOrElse($default)

map(Closure $expression)getOrElse($default)

Some($expression($this->content)

$this->content

Page 59: Why async and functional programming in PHP7 suck and how to get overr it?

Option

Option

NoneSomemap(Closure $expression)getOrElse($default)

map(Closure $expression)getOrElse($default)

None

$default

Page 60: Why async and functional programming in PHP7 suck and how to get overr it?

public function findByEmail(string $email) : User{ $user = $this->findOneBy(['email' => $email]); if (!$user instanceof User) { throw new NotFoundException("oh my"); } return $user;}

try { return new Response(findByEmail($email), HTTP_OK);} catch (NotFoundException $exception) { return new Response([], HTTP_NOT_FOUND);}

Page 61: Why async and functional programming in PHP7 suck and how to get overr it?

public function findByEmail(string $email) : User{ $user = $this->findOneBy(['email' => $email]); if (!$user instanceof User) { throw new NotFoundException("oh my"); } return $user;}

try { return new Response(findByEmail($email), HTTP_OK);} catch (NotFoundException $exception) { return new Response([], HTTP_NOT_FOUND);}

public function findByEmail(string $email) : Option{ return Option::of($this->findOneBy(['email' => $email]));}

return findByEmail($email)) ->map(function (User $user) { return new Response($user, HTTP_OK); }) ->getOrElse(new Response('', HTTP_NOT_FOUND));

Page 62: Why async and functional programming in PHP7 suck and how to get overr it?

public function findByEmail(string $email) : User{ $user = $this->findOneBy(['email' => $email]); if (!$user instanceof User) { throw new NotFoundException("oh my"); } return $user;}

try { return new Response(findByEmail($email), HTTP_OK);} catch (NotFoundException $exception) { return new Response([], HTTP_NOT_FOUND);}

public function findByEmail(string $email) : Option{ return Option::of($this->findOneBy(['email' => $email]));}

return findByEmail($email)) ->map(function (User $user) { return new Response($user, HTTP_OK); }) ->getOrElse(new Response('', HTTP_NOT_FOUND));

map

Page 63: Why async and functional programming in PHP7 suck and how to get overr it?

OptionHow about nesting

Page 64: Why async and functional programming in PHP7 suck and how to get overr it?

public function findByEmail(string $email) : Option{ return Option::of($this->findOneBy(['email' => $email]));}

public function postalCode(string $email, PostalCode $default) : PostalCode{

return findByEmail($email)->map(function (User $user) {

return $user->getProfile()->getAdress()->getPostalCode();})->getOrElse($default);

}

Page 65: Why async and functional programming in PHP7 suck and how to get overr it?

public function postalCode(string $email, PostalCode $default) : PostalCode{

return findByEmail($email);->map(function (User $user) {

return $user->getProfile()->getAdress()->getPostalCode();})->getOrElse($default);

}

Page 66: Why async and functional programming in PHP7 suck and how to get overr it?

public function postalCode(string $email, PostalCode $default) : PostalCode{

return findByEmail($email)->flatMap(function (User $user) {

return $user->getProfile();})

->flatMap(function (UserProfile $userProfile) {return $userProfile->getAdress();

}) ->flatMap(function (Adress $adress) {

return $adress->getPostalCode();})->getOrElse($default);

}

Page 67: Why async and functional programming in PHP7 suck and how to get overr it?

public function postalCode(string $email, PostalCode $default) : PostalCode{

return findByEmail($email) ->flatMap(function (User $user) {

return $user->getProfile();})

->flatMap(function (UserProfile $userProfile) {return $userProfile->getAdress();

}) ->flatMap(function (Adress $adress) {

return $adress->getPostalCode();})->getOrElse($default);

}

flatMap

Page 68: Why async and functional programming in PHP7 suck and how to get overr it?

Few rules to make your code functional

Page 69: Why async and functional programming in PHP7 suck and how to get overr it?

Do not use

:) reassignments:) if:) null❏ for❏ foreach

Page 70: Why async and functional programming in PHP7 suck and how to get overr it?

Shortened notation for anonymous functions

Page 71: Why async and functional programming in PHP7 suck and how to get overr it?

public function displayNameForUser(string $email) : string{ return $this ->userRepository ->findByEmail($email) ->flatMap(function (User $user) { return $user->getFirstName(); }) ->getOrCall(function () use (string $email) : string {

return $this->getSomethingElseWith($email);});

}

Page 72: Why async and functional programming in PHP7 suck and how to get overr it?

public function displayNameForUser(string $email) : string{ return $this ->userRepository ->findByEmail($email) ->flatMap(function (User $user) { return $user->getFirstName(); }) ->getOrCall(function () use (string $email) : string {

return $this->getSomethingElseWith($email);});

}

Page 73: Why async and functional programming in PHP7 suck and how to get overr it?

public displayNameForUser(string email) : stringuserRepository

->findByEmail(email)->flatMap(_->getFirstName)->getOrCall(getSomethingElseWith(email))

:(

Page 74: Why async and functional programming in PHP7 suck and how to get overr it?

public def displayNameForUser(email : string) : string =userRepository

.findByEmail(email)

.flatMap(_.getFirstName)

.getOrElse(_ => getSomethingElseWith(email))\:)

Page 75: Why async and functional programming in PHP7 suck and how to get overr it?

public function displayNameForUser(string $email) : string{ return $this ->userRepository ->findByEmail($email) ->flatMap(Extract($user)->getFirstName()) ->getOrCall(Extract($this)->getSomethingElseWith($email));}

NYI

\:)

Page 76: Why async and functional programming in PHP7 suck and how to get overr it?

Generic types

Page 77: Why async and functional programming in PHP7 suck and how to get overr it?

public function maybeSomething(string $email) : Option{ ...}

Page 78: Why async and functional programming in PHP7 suck and how to get overr it?

/*** @return Option<string>*/public function maybeSomething(string $email) : Option{ ...}

https://github.com/phpDocumentor/fig-standards/blob/master/proposed/phpdoc.md

:(

Page 79: Why async and functional programming in PHP7 suck and how to get overr it?

public function maybeSomething(string $email) : Option<string>{ ...}

:o

Page 80: Why async and functional programming in PHP7 suck and how to get overr it?

public function maybeSomething(string $email) : Option<string>{ ...}

❏ Version: 0.4.0❏ Date: 2016-01-06❏ Author:

❏ Ben Scholzen 'DASPRiD' [email protected],❏ Rasmus Schultz [email protected]

❏ Status: Draft❏ First Published at: http://wiki.php.net/rfc/generics

:(

Page 81: Why async and functional programming in PHP7 suck and how to get overr it?

public function maybeSomething(string $email) : Option<string>{ ...}

WANT TO EARN EXTRA $1020 ?https://www.bountysource.com/issues/20553561-add-generics-support:~|

Page 82: Why async and functional programming in PHP7 suck and how to get overr it?

Syntax doesn’t matterthinking does

Erlang guys

Page 83: Why async and functional programming in PHP7 suck and how to get overr it?

What do I miss in PHP7 that Scala luckily has?

Page 84: Why async and functional programming in PHP7 suck and how to get overr it?

:/ Immutability by default:) Objects cloning:) Options❏ Either❏ Future❏ Parallel collections❏ Tail recurrency

:( Generic types:( Arrow functions❏ Pattern matching / case classes

Page 85: Why async and functional programming in PHP7 suck and how to get overr it?

Either

Page 86: Why async and functional programming in PHP7 suck and how to get overr it?

Either

Either

RightLeft

Page 87: Why async and functional programming in PHP7 suck and how to get overr it?

Either

Either

RightLeftleft(Closure $expr): Eitherright(Closure $expr): Eitherget()

left(Closure $expr): Eitherright(Closure $expr): Eitherget()

Page 88: Why async and functional programming in PHP7 suck and how to get overr it?

Either

Either

RightLeftleft(Closure $expr): Eitherright(Closure $expr): Eitherget()

left(Closure $expr): Eitherright(Closure $expr): Eitherget()

SEMANTICS!

Page 89: Why async and functional programming in PHP7 suck and how to get overr it?

What do I miss in PHP7 that Scala luckily has?

Page 90: Why async and functional programming in PHP7 suck and how to get overr it?

:/ Immutability by default:) Objects cloning:) Options:) Either❏ Future❏ Parallel collections❏ Tail recurrency

:( Generic types:( Arrow functions❏ Pattern matching / case classes

Page 91: Why async and functional programming in PHP7 suck and how to get overr it?

Pattern Matching

Page 92: Why async and functional programming in PHP7 suck and how to get overr it?

Pattern matching

Result

Variant 1

Variant 2

Variant 3

Variant N

...

Page 93: Why async and functional programming in PHP7 suck and how to get overr it?

return (Match::of($someKindResult))->match(

new Case(IvalidInput::class, new Response('', HTTP_BAD_REQUEST)),new Case(NotFound::class, new Response('',HTTP_NOT_FOUND),new Default(function () use ($someKindResult) {

return new Response($someKindResult, HTTP_OK);})

);

Page 94: Why async and functional programming in PHP7 suck and how to get overr it?

What do I miss in PHP7 that Scala luckily has?

Page 95: Why async and functional programming in PHP7 suck and how to get overr it?

:/ Immutability by default:) Objects cloning:) Options:) Either❏ Future❏ Parallel collections❏ Tail recurrency

:( Generic types:( Arrow functions:)/:( Pattern matching / case classes

Page 96: Why async and functional programming in PHP7 suck and how to get overr it?

Parallel collections

Page 97: Why async and functional programming in PHP7 suck and how to get overr it?

Parallel collections

Collection

N...3210

Page 98: Why async and functional programming in PHP7 suck and how to get overr it?

public function beautifulMultiplyOddsBy( array $input, float $multiplication) : ListCollection{ return (new ListCollection($input)) ->filter(function ($number) { return $number % 2 !== 0; }) ->map(function ($number) use ($multiplication) { return $number * $multiplication; });}

Page 99: Why async and functional programming in PHP7 suck and how to get overr it?

public function accumulatedText(array $words) : string { $text = ''; foreach ($words as $word) { $text .= $word . ' '; } return $text;}

public function accumulatedText(array $words) : string { return (new ListCollection($words)) ->fold('', function (string $acumulator, string $word) { return $acumulator . $word . ' '; });}

Page 100: Why async and functional programming in PHP7 suck and how to get overr it?

(new ListCollection([1,2,3,4]))->tail(); //ListCollection([2,3,4])

(new ListCollection([1,2,3,4]))->every(2); //ListCollection([2,4])

(new ListCollection([1,2,3,4]))->groups(2);ListCollection([

ListCollection([1,2]),ListCollection([3,4]),

])

Page 101: Why async and functional programming in PHP7 suck and how to get overr it?

Few rules to make your code functional

Page 102: Why async and functional programming in PHP7 suck and how to get overr it?

Do not use

:) reassignments:) if:) null:) for:) foreach

Page 103: Why async and functional programming in PHP7 suck and how to get overr it?

Parallelism vs Concurrency

Page 104: Why async and functional programming in PHP7 suck and how to get overr it?
Page 105: Why async and functional programming in PHP7 suck and how to get overr it?
Page 106: Why async and functional programming in PHP7 suck and how to get overr it?

Future

Page 107: Why async and functional programming in PHP7 suck and how to get overr it?

public function nonBlockingGet(string $id): Future{ ...}

public function exampleAction(string $id1) : Response{ return $this ->nonBlockingService ->nonBlockingGet($id) ->map(function (NonBlockingGetResult $output) { return new Response($output); }) ->await();}

Page 108: Why async and functional programming in PHP7 suck and how to get overr it?

public function nonBlockingGet(string $id): Future{ ...}

public function exampleAction(string $id1) : Response{ return $this ->nonBlockingService ->nonBlockingGet($id) ->map(function (NonBlockingGetResult $output) { return new Response($output); }) ->await();}

Future<NonBlockingGetResult>

NYI

Page 109: Why async and functional programming in PHP7 suck and how to get overr it?

public function nonBlockingGet(string $id): Future{ ...}

public function exampleAction(string $id1) : Response{ return $this ->nonBlockingService ->nonBlockingGet($id) ->map(function (NonBlockingGetResult $output) { return new Response($output); }) ->await();}

Future<NonBlockingGetResult>

NYI

Future<Response>

Page 110: Why async and functional programming in PHP7 suck and how to get overr it?

public function nonBlockingGet(string $id): Future{ ...}

public function exampleAction(string $id1) : Response{ return $this ->nonBlockingService ->nonBlockingGet($id) ->map(function (NonBlockingGetResult $output) { return new Response($output); }) ->await();}

Future<NonBlockingGetResult>

NYI

Future<Response>

Response

Page 111: Why async and functional programming in PHP7 suck and how to get overr it?

public function nonBlockingGet(string $id): Future{ ...}

public function exampleAction(string $id1, string $id2, string $id3) : Response{ return Future::all([ $this->nonBlockingService1->nonBlockingGet($id1), $this->nonBlockingService2->nonBlockingGet($id2), $this->nonBlockingService3->nonBlockingGet($id3), ]) ->map(function ($output) { return new Response($output); }) ->await();}

NYI

Page 112: Why async and functional programming in PHP7 suck and how to get overr it?

Future & Parallel collections

Page 113: Why async and functional programming in PHP7 suck and how to get overr it?

use PhpSlang\Collection\ListCollection;...public function beautifulMultiplyBy(array $input, float $multiplication) : ListCollection{ return (new ListCollection($input)) ->map(function ($number) use ($multiplication) { return $number * $multiplication; });}

Page 114: Why async and functional programming in PHP7 suck and how to get overr it?

use PhpSlang\Collection\ParallelListCollection;...public function beautifulMultiplyBy(array $input, float $multiplication) : ParallelListCollection{ return (new ParallelListCollection($input)) ->map(function ($number) use ($multiplication) { return $number * $multiplication; });}

Page 115: Why async and functional programming in PHP7 suck and how to get overr it?

use PhpSlang\Collection\ListCollection;...public function asyncChainedComputationExample(array $input) : ListCollection{ return (new ListCollection($input))

->map($this->transformationOne());}

use PhpSlang\Collection\ParallelListCollection;...public function asyncChainedComputationExample(array $input) : ParallelListCollection{ return (new ParallelListCollection($input))

->map($this->transformationOne());}

Page 116: Why async and functional programming in PHP7 suck and how to get overr it?

use PhpSlang\Collection\ListCollection;...public function asyncChainedComputationExample(array $input) : ListCollection{ return (new ListCollection($input))

->map($this->transformationOne());}

use PhpSlang\Collection\ParallelListCollection;...public function asyncChainedComputationExample(array $input) : ParallelListCollection{ return (new ParallelListCollection($input))

->map($this->transformationOne());}

Page 117: Why async and functional programming in PHP7 suck and how to get overr it?

use PhpSlang\Collection\ParallelListCollection;...public function asyncChainedComputationExample(array $input) : ParallelListCollection{ return (new ParallelListCollection($input))

->map($this->transformationOne());}

CPU vs IO

Page 118: Why async and functional programming in PHP7 suck and how to get overr it?

use PhpSlang\Collection\ParallelListCollection;...public function asyncChainedComputationExample(array $input) : ParallelListCollection{ return (new ParallelListCollection($input))

->map($this->transformationOne())

->map($this->transformationTwo())

->map($this->transformationThree();}

Page 119: Why async and functional programming in PHP7 suck and how to get overr it?

use PhpSlang\Collection\ParallelListCollection;...public function asyncChainedComputationExample(array $input) : ParallelListCollection{ return (new ParallelListCollection($input)) ->map(function ($number) { return new Some($number) ->map($this->transformationOne())

->map($this->transformationTwo())

->map($this->transformationThree()

->get(); });}

Page 120: Why async and functional programming in PHP7 suck and how to get overr it?

use PhpSlang\Collection\ParallelListCollection;…public function asyncChainedComputationExample(array $input) : ParallelListCollection{ return (new ParallelListCollection($input)) ->map(function ($number) { return new Some($number) ->map($this->transformationOne())

->map($this->transformationTwo())

->map($this->transformationThree()

->get(); });}

Page 121: Why async and functional programming in PHP7 suck and how to get overr it?

What do I miss in PHP7 that Scala luckily has?

Page 122: Why async and functional programming in PHP7 suck and how to get overr it?

:/ Immutability by default:) Objects cloning:) Options:) Either:/ Future:) Parallel collections❏ Tail recurrency

:( Generic types:( Arrow functions:)/:( Pattern matching / case classes

Page 123: Why async and functional programming in PHP7 suck and how to get overr it?

Tail recurrency

Page 124: Why async and functional programming in PHP7 suck and how to get overr it?

def fibonacci(index : Int) : Int =index match { case 0 | 1 => index case _ => fibonacci(index - 1 ) + fibonacci(index - 2)}

function fibonacci(int $index) : int{ return in_array($index, [0, 1]) ? $index : fibonacci($index - 1) + fibonacci($index - 2);}

Page 125: Why async and functional programming in PHP7 suck and how to get overr it?

def fibonacci(index : Int) : Int =index match { case 0 | 1 => index case _ => fibonacci(index - 1 ) + fibonacci(index - 2)}

function fibonacci(int $index) : int{ return in_array($index, [0, 1]) ? $index : fibonacci($index - 1) + fibonacci($index - 2);}

echo fibonacci(123123123123);

Fatal error: Maximum function nesting level of '...' reached, aborting!

Page 126: Why async and functional programming in PHP7 suck and how to get overr it?

ini_set('xdebug.max_nesting_level', 9999999);

?

Page 127: Why async and functional programming in PHP7 suck and how to get overr it?

def fibonacci(index: Int): Int = { var a = 0 var b = 1 var i = 0

while (i < index) { val c = a + b a = b b = c i = i + 1 } return a}

function fibonacci(int $index) : int{ $a = 0; $b = 1; $i = 0;

while ($i < $index) { $c = $a + $b; $a = $b; $b = $c; $i += 1; } return $a;}

Page 128: Why async and functional programming in PHP7 suck and how to get overr it?

def recursiveFibonacci(n: Int, a:Int, b:Int): Int =n match { case 0 => a case _ => recursiveFibonacci( n-1, b, a+b ) }

def fibonacci( n : Int) : Int = recursiveFibonacci( n, 0, 1)

function recursiveFibonacci(int $n, int $a, int $b) { return ($n == 0) ? $a : recursiveFibonacci($n - 1, $b, $a + $b);}

function fibonacci(int $n) : int{ return recursiveFibonacci($n, 0, 1);}

Page 129: Why async and functional programming in PHP7 suck and how to get overr it?

def fibonacci(index : Int) : Int =index match { case 0 | 1 => index case _ => fibonacci(index - 1 ) + fibonacci(index - 2)}

function fibonacci(int $index) : int{ return in_array($index, [0, 1]) ? $index : fibonacci($index - 1) + fibonacci($index - 2);}

Page 130: Why async and functional programming in PHP7 suck and how to get overr it?

@tailrecdef recursiveFibonacci(n: Int, a:Int, b:Int): Int =n match { case 0 => a case _ => recursiveFibonacci( n-1, b, a+b ) }

def fibonacci( n : Int) : Int = recursiveFibonacci( n, 0, 1)

function recursiveFibonacci(int $n, int $a, int $b) { return ($n == 0) ? $a : recursiveFibonacci($n - 1, $b, $a + $b);}

function fibonacci(int $n) : int{ return recursiveFibonacci($n, 0, 1);} :(:)

Page 131: Why async and functional programming in PHP7 suck and how to get overr it?

Tail recurrencyTrampolines

Page 132: Why async and functional programming in PHP7 suck and how to get overr it?

Recurrency

Page 133: Why async and functional programming in PHP7 suck and how to get overr it?

Recurrency Trampoline

Page 134: Why async and functional programming in PHP7 suck and how to get overr it?

function recursiveFibonacci(int $n, int $a, int $b) { return ($n == 0) ? $a : recursiveFibonacci($n - 1, $b, $a + $b);}

function fibonacci($n){ return recursiveFibonacci($n, 0, 1);}

Page 135: Why async and functional programming in PHP7 suck and how to get overr it?

function recursiveFibonacci(int $n, int $a, int $b) { return ($n == 0) ? new Done($a) : new Bounce(function () use ($n, $b, $a) { return recursiveFibonacci($n - 1, $b, $a + $b); });}

function fibonacci($n){ return (new Trampoline(function () use ($n) { return recursiveFibonacci($n, 0, 1); }))->run();}

Page 136: Why async and functional programming in PHP7 suck and how to get overr it?

Recurrency Trampoline

Page 137: Why async and functional programming in PHP7 suck and how to get overr it?

What do I miss in PHP7 that Scala luckily has?

Page 138: Why async and functional programming in PHP7 suck and how to get overr it?

:/ Immutability by default:) Objects cloning:) Options:) Either:/ Future:) Parallel collections:) Tail recurrency

:( Generic types:( Arrow functions:)/:( Pattern matching / case classes

Page 139: Why async and functional programming in PHP7 suck and how to get overr it?
Page 140: Why async and functional programming in PHP7 suck and how to get overr it?

Conclusions

● Don’t be afraid of monads● Care about transparency (especially referential)

● Learn Haskell, Clojure, Scala, F#, JavaScript -> TypeScript

Page 141: Why async and functional programming in PHP7 suck and how to get overr it?

Witek [email protected]

http://phpslang.io