Skip to content

Instantly share code, notes, and snippets.

@twslade
Created December 1, 2016 15:22
Show Gist options
  • Save twslade/4df7b42d596b0dff48a17853d8b57515 to your computer and use it in GitHub Desktop.
Save twslade/4df7b42d596b0dff48a17853d8b57515 to your computer and use it in GitHub Desktop.
<?php
require '/home/thomas/projects/functional-php/vendor/autoload.php';
//Manually currying
$test = function($start){
return function($length) use ($start){
return function($string) use ($start, $length){
return substr($string, $start, $length);
};
};
};
$new = $test(0);
$new2 = $new(2);
var_dump($new2('testing'));
//Composition
function compose($a, $b){
return function() use ($a, $b){
$args = func_get_args();
return $b(call_user_func_array($a, $args));
};
}
$a = function($val){ return str_word_count($val); };
$b = function($val){ return $val - 2; };
$c = compose($a, $b);
var_dump($c('How many word does this sentence contain'));
use Functional as F;
$prods = array(
array("sku" => 1234, "weight" => 1, "price" => '4.50', "qty" => 10, "cost" => 3.75),
array("sku" => "abcd", "weight" => 0.5, "price" => '10', "qty" => 0, "cost" => 10),
array("sku" => "shirt", "weight" => 0.1, "price" => '30', "qty" => 45, "cost" => 25),
array("sku" => "shoes", "weight" => 2, "price" => '400', "qty" => 1, "cost" => 200)
);
function functionalSort($collection, $callback){
uasort($collection, $callback);
return $collection;
}
$mostExpensiveProduct = F\first(
functionalSort(
F\Pluck($prods, "price"),
function($a, $b){
return $a < $b;
}
)
);
var_dump($mostExpensiveProduct);
$maxSalesAvailable = F\reduce_left(
$prods,
function($value, $idx, $collection, $result){
return $result + $value['qty'] * $value['price'];
}
);
var_dump($maxSalesAvailable);
$mostProfitAvailableFunc = function($cost, $price, $qty){
return ($price * $qty) - ($cost * $qty);
};
$maxProfitAvailable = F\sum(
F\zip(
F\pluck($prods, 'cost'),
F\pluck($prods, 'price'),
F\pluck($prods, 'qty'),
$mostProfitAvailableFunc
)
);
var_dump($maxProfitAvailable);
$test = function(){
foreach(range(2,10) as $x){
yield $x;
}
};
var_dump(iterator_to_array($test()));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment