lstrojny / functional-php

Primitives for functional programming in PHP
MIT License
1.98k stars 204 forks source link

Add converge function #186

Closed win0err closed 5 years ago

win0err commented 5 years ago

Converge

Accepts a converging function and a list of branching functions and returns a new function. When invoked, this new function is applied to some arguments, and each branching function is applied to those same arguments. The results of each branching function are passed as arguments to the converging function to produce the return value.

<?php
converge('intdiv', ['max', 'min'])([2, 3, 4, 5, 6]); // 3

JS ramda analog

Erikvv commented 5 years ago

What is the reason to do this instead of equivalent code which is also functional:

function middle(array $data) {
    return intdiv(max($data), min($data));
}

middle([2, 3, 4, 5, 6]);

Converge would be useful if you don't know which functions to apply beforehand but I can't think of such case.

Do you have a good usecase?

win0err commented 5 years ago

What is the reason to do this instead of equivalent code which is also functional:

function middle(array $data) {
    return intdiv(max($data), min($data));
}

middle([2, 3, 4, 5, 6]);

Converge would be useful if you don't know which functions to apply beforehand but I can't think of such case.

Do you have a good usecase?


<?php
// sma() function is taken from here: 
// https://github.com/markrogoyski/math-php/blob/master/src/Statistics/Average.php#L650
$sma = curry_n(2, flip('sma'));

$processingFunction = fn (...$args) => array_map(curry('implode')(' → '), $args); $getChart = converge( $processingFunction, [$sma(1), $sma(2), $sma(4), $sma(8)] ); // vs. $getChart2 = function ($data) use ($sma) { return [ implode(' → ', $sma(1)($data)), implode(' → ', $sma(2)($data)), implode(' → ', $sma(4)($data)), implode(' → ', $sma(8)($data)), ]; };

$chart = $getChart([1, 2, 3, 4, 5, 6, 7, 8, 9]);


Pros of `converge` is a more functional approach. It's easy to add another function like `$sma(42)` to the list of branching functions.
lstrojny commented 5 years ago

Awesome, thank you!