Skip to content

Instantly share code, notes, and snippets.

@coderofsalvation
Last active January 7, 2016 20:04
Show Gist options
  • Save coderofsalvation/b011bb0f6789044b4da1 to your computer and use it in GitHub Desktop.
Save coderofsalvation/b011bb0f6789044b4da1 to your computer and use it in GitHub Desktop.
highorder-functions for php 5.3 and higher with simple datastore example
<?php
include_once("highorderfuncs.php");
/*
* simple datastore example
*/
$createDefaultItem = function($key){
return (object)array("title" => $key);
};
$set = function($store,$key,$value){
$store->$key = $value;
};
$get = function($store,$key){
return isset($store->$key) ? $store->$key : false;
};
/*
* highorder functions using curry
*/
$store = (object)array();
$getFromStore = curry( $get,$store);
$saveToStore = curry( $set,$store);
$saveToStore("foo","bar");
print_r( $getFromStore("foo") );
/*
* highorder functions using compose (piping)
*/
$getDefaultItemAndSave = compose( $createDefaultItem, curry( $saveToStore, time() ) );
$getOrCreateItem = either( $getFromStore, $getDefaultItemAndSave );
print_r( $getOrCreateItem("newitem") );
print_r( $store );
<?php
/* high order functions utils for php */
// curry!
// example: $arrayToLines = curry( implode, "\n" );
// $arrayToLines( ["one","two"] );
function curry($fn, $arg, $obj = null) {
return function() use ($fn, $arg, $obj) {
$args = func_get_args();
array_unshift($args, $arg);
if($obj) {
$fn = array($obj, $fn);
}
return call_user_func_array($fn, $args);
};
}
// This function allows creating a new function from two functions passed into it
function compose(&$f, &$g) {
// Return the composed function
return function() use($f,$g) {
// Get the arguments passed into the new function
$x = func_get_args();
// Call the function to be composed with the arguments
// and pass the result into the first function.
return $f(call_user_func_array($g, $x));
};
}
// Convenience wrapper for mapping
function map(&$data, &$f) {
return array_map($f, $data);
}
// Convenience wrapper for filtering arrays
function filter(&$data, &$f) {
return array_filter($data, $f);
}
// Convenience wrapper for reducing arrays
function fold(&$data, &$f) {
return array_reduce($data, $f);
}
function either($a,$b){
return function($c) use($a,$b) { $a($c) || $b($c); };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment