From 4c44cac03c6bc4b40a6cd2f47bd31cdc6885973a Mon Sep 17 00:00:00 2001 From: rod Date: Mon, 2 Jul 2012 16:46:56 +0100 Subject: [PATCH] added function for partial application --- test/FunctionsTest.php | 14 +++++++++++++- underscore.php | 11 +++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/test/FunctionsTest.php b/test/FunctionsTest.php index 9fa627a..4945e07 100644 --- a/test/FunctionsTest.php +++ b/test/FunctionsTest.php @@ -193,4 +193,16 @@ public function testAfter() { $func(); $this->assertEquals('x', $str); } -} \ No newline at end of file + + function testPartial() { + // partial once + $f = function( $x, $y ) { return $x + $y; }; + $f2 = __::partial( $f, 2 ); + $this->assertEquals( 5, $f2(3) ); + + // partial on a partial + $f3 = __::partial( $f2, 4 ); + $this->assertEquals( 6, $f3() ); + } + +} diff --git a/underscore.php b/underscore.php index 1482eed..54dd251 100644 --- a/underscore.php +++ b/underscore.php @@ -1069,6 +1069,17 @@ public function after($count=null, $function=null) { }; return self::_wrap(($count) ? $func : $func()); } + + + // creates a partially applied version of the function + public function partial() { + $origArgs = func_get_args(); + $f = array_shift( $origArgs ); + return function() use ( $f, $origArgs ) { + $allArgs = array_merge( $origArgs, func_get_args() ); + return call_user_func_array( $f, $allArgs ); + }; + } // Singleton