Logo

Programming-Idioms

History of Idiom 37 > diff from v30 to v31

Edit summary for version 31 by programming-idioms.org:
[PHP] Comments emphasis

Version 30

2018-08-23, 01:48:53

Version 31

2018-09-06, 19:58:30

Idiom #37 Currying

Transform a function that takes multiple arguments into a function for which some of the arguments are preset.

Idiom #37 Currying

Transform a function that takes multiple arguments into a function for which some of the arguments are preset.

Extra Keywords
curry
Extra Keywords
curry
Code
function curry($f, ...$argsCurried) {	
	return function(...$args) use($f, $argsCurried) {
		$finalArgs = array_merge($argsCurried, $args);
		return call_user_func_array($f, $finalArgs);
	};
}

function add($n1, $n2) {
	return $n1 + $n2;
}

$addFive = curry('add', 5);

echo $addFive(2), PHP_EOL;
echo $addFive(-5), PHP_EOL;
Code
function curry($f, ...$argsCurried) {	
	return function(...$args) use($f, $argsCurried) {
		$finalArgs = array_merge($argsCurried, $args);
		return call_user_func_array($f, $finalArgs);
	};
}

function add($n1, $n2) {
	return $n1 + $n2;
}

$addFive = curry('add', 5);

echo $addFive(2), PHP_EOL;
echo $addFive(-5), PHP_EOL;
Comments bubble
curry returns an anonymous function or closure (http://php.net/manual/en/functions.anonymous.php).
Comments bubble
curry returns an anonymous function or closure (http://php.net/manual/en/functions.anonymous.php).
Doc URL
https://secure.php.net/manual/en/function.call-user-func-array.php
Doc URL
https://secure.php.net/manual/en/function.call-user-func-array.php
Demo URL
https://3v4l.org/VufKK
Demo URL
https://3v4l.org/VufKK