473,385 Members | 1,610 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Currying a function

Hello,

I'd like to know if it's possible to curry a function in PHP? That is,
is there some built-in mechanism for it, or is it possible to create a
function that does the currying?

I've tried something myself, and come up with the following:

---

function curry($fnc, $args) {
$callargs = "";
foreach ($args as $arg) {
if (is_string($arg))
$callargs .= '"' . $arg . '"';
else
$callargs .= $arg;

$callargs .= ', ';
}

$callargs .= '$x';

return create_function('$x', sprintf('return %s(%s);', $fnc,
$callargs));
}

---

Basically, this function builds a new (lambda) function that calls the
previous function, but with the parameters to the curry transformed to
literals (causing the number of arguments to be reduced). This works
fine; I can now do the following:

---

function times($a, $b) {
return $a * $b;
}

$t5 = curry("times", array(5));

echo $t5(3); // Outputs `15'

---

This works alright, but only for strings and integers. At the moment, I
need to curry an object, and the function only receives the string
`Object' as a parameter (which is of course logical). And actually, the
method I used has another limitation; the resulting function only has
one parameter left. For what I'm using it right now, that's not a
problem, but it's not very generic.

Ultimately, I guess that for my purposes, I could resort to using
classes instead of functions, but I would very much like to get the
currying approach working, if at all possible.

So my question is: can currying be done in PHP with any variable type
(and preferably with any amount of parameters)?

Thanks in advance.

Kind regards,
Rico Huijbers
Jul 17 '05 #1
8 2503
Rico Huijbers wrote:

I'd like to know if it's possible to curry a function in PHP?


For people who (like myself) have never heard of "currying" before
today, here is a link which explains what "currying" is (it does not
have anything to do with Indian cuisine):

http://www.fact-index.com/c/cu/currying.html

In this case, I think using classes would be much easier, but perhaps it
is because those are familiar to me, while "currying" is not.

bblackmoor
2004-11-08
Jul 17 '05 #2
Rico Huijbers <E.************@REMOVEstudent.tue.nl> treated the
lovely people of comp.lang.php with the following stuff:
Hello,

I'd like to know if it's possible to curry a function in PHP?
That is, is there some built-in mechanism for it, or is it
possible to create a function that does the currying?


Take a look at the func_get_args() function. If you haven't already
that is.

--
Phil Roberts | http://www.flatnet.net/

You're wrong. And you're a grotesquely ugly freak.
Jul 17 '05 #3
On Tue, 09 Nov 2004 16:47:30 +0100, Rico Huijbers
<E.************@REMOVEstudent.tue.nl> wrote:
I'd like to know if it's possible to curry a function in PHP? That is,
is there some built-in mechanism for it, or is it possible to create a
function that does the currying?
Not built in.
I've tried something myself, and come up with the following:

---

function curry($fnc, $args) {
$callargs = "";
foreach ($args as $arg) {
if (is_string($arg))
$callargs .= '"' . $arg . '"';
else
$callargs .= $arg;

$callargs .= ', ';
}

$callargs .= '$x';

return create_function('$x', sprintf('return %s(%s);', $fnc,
$callargs));
}

---

Basically, this function builds a new (lambda) function that calls the
previous function, but with the parameters to the curry transformed to
literals (causing the number of arguments to be reduced). This works
fine; I can now do the following:

---

function times($a, $b) {
return $a * $b;
}

$t5 = curry("times", array(5));

echo $t5(3); // Outputs `15'
Looks like a good start.
This works alright, but only for strings and integers. At the moment, I
need to curry an object, and the function only receives the string
`Object' as a parameter (which is of course logical). And actually, the
method I used has another limitation; the resulting function only has
one parameter left. For what I'm using it right now, that's not a
problem, but it's not very generic.

Ultimately, I guess that for my purposes, I could resort to using
classes instead of functions, but I would very much like to get the
currying approach working, if at all possible.

So my question is: can currying be done in PHP with any variable type
(and preferably with any amount of parameters)?


You're building up your function at the moment with string concatenation -
which as well as not handling objects, may well fall over with escaping issues
(quotes and backslashes and so on).

What about using serialisation, since that can store objects; pass the
serialised form of the curried arguments into the lambda function, which then
at call time deserialises them and appends any further arguments, before
calling the original base function.

How about:

<?php
function curry($fnc) {
$args = func_get_args();
array_shift($args);

$lambda = sprintf(
'$args = func_get_args(); ' .
'return call_user_func_array(\'%s\', array_merge(unserialize(\'%s\'),
$args));',
$fnc, serialize($args)
);
return create_function('', $lambda);
}

function times($a, $b) {
return $a * $b;
}

$t5 = curry('times', 5);
echo $t5(3); // Outputs '15'

print "<hr>";

class ExampleObject {
var $attr = 1;
}

$obj = new ExampleObject();

function printAttr($title, $obj)
{
print "$title {$obj->attr}<br>";
}

$paAttr = curry('printAttr', 'title');
echo $paAttr($obj); // outputs 'title 1'

print "<hr>";

function add($a, $b, $c, $d)
{
return $a + $b + $c + $d;
}

$a = curry('add', 1, 2);
echo $a(3, 4); // outputs 10
?>

--
Andy Hassall / <an**@andyh.co.uk> / <http://www.andyh.co.uk>
<http://www.andyhsoftware.co.uk/space> Space: disk usage analysis tool
Jul 17 '05 #4
Andy Hassall wrote:
You're building up your function at the moment with string concatenation -
which as well as not handling objects, may well fall over with escaping issues
(quotes and backslashes and so on).

What about using serialisation, since that can store objects; pass the
serialised form of the curried arguments into the lambda function, which then
at call time deserialises them and appends any further arguments, before
calling the original base function.

How about:

<?php
function curry($fnc) {
$args = func_get_args();
array_shift($args);

$lambda = sprintf(
'$args = func_get_args(); ' .
'return call_user_func_array(\'%s\', array_merge(unserialize(\'%s\'),
$args));',
$fnc, serialize($args)
);
return create_function('', $lambda);
}

function times($a, $b) {
return $a * $b;
}

$t5 = curry('times', 5);
echo $t5(3); // Outputs '15'

print "<hr>";

class ExampleObject {
var $attr = 1;
}

$obj = new ExampleObject();

function printAttr($title, $obj)
{
print "$title {$obj->attr}<br>";
}

$paAttr = curry('printAttr', 'title');
echo $paAttr($obj); // outputs 'title 1'

print "<hr>";

function add($a, $b, $c, $d)
{
return $a + $b + $c + $d;
}

$a = curry('add', 1, 2);
echo $a(3, 4); // outputs 10
?>


You are truly a master of the black arts ;).

Thanks a bunch! Using serialization would never have occurred to me.
Your solution is great, though. I noticed you didn't try including an
object in the curry, but I just tested it and it works like a charm as
well (except for the minor detail that it will be a copy, and not a
reference).

I like it. Thanks again.

Regards,
Rico
Jul 17 '05 #5
On Wed, 10 Nov 2004 00:06:56 +0100, Rico Huijbers
<E.************@REMOVEstudent.tue.nl> wrote:
You are truly a master of the black arts ;).

Thanks a bunch! Using serialization would never have occurred to me.
Your solution is great, though. I noticed you didn't try including an
object in the curry, but I just tested it and it works like a charm as
well (except for the minor detail that it will be a copy, and not a
reference).

I like it. Thanks again.


Been a while since I'd last heard of currying, since university. We did
currying in the Haskell functional programming course, appropriate since both
Haskell and currying are named after the same person, Haskell Curry.

I'm not sure if there's a way you can pass a reference into the curry, since
serialisation always makes a copy. Perhaps you could do it if you resorted to
storing it in a global array and passing the key in - *bleh* :-)

--
Andy Hassall / <an**@andyh.co.uk> / <http://www.andyh.co.uk>
<http://www.andyhsoftware.co.uk/space> Space: disk usage analysis tool
Jul 17 '05 #6
Andy Hassall wrote:
I'm not sure if there's a way you can pass a reference into the curry, since
serialisation always makes a copy. Perhaps you could do it if you resorted to
storing it in a global array and passing the key in - *bleh* :-)


Remember that you can create a callable object+method reference by
array( &$object, 'methodname' ). Objects can have member variables which
can be references...

-- brion vibber (brion @ pobox.com)
Jul 17 '05 #7
On Tue, 09 Nov 2004 23:34:36 -0800, Brion Vibber <br***@pobox.com> wrote:
Andy Hassall wrote:
I'm not sure if there's a way you can pass a reference into the curry, since
serialisation always makes a copy. Perhaps you could do it if you resorted to
storing it in a global array and passing the key in - *bleh* :-)


Remember that you can create a callable object+method reference by
array( &$object, 'methodname' ). Objects can have member variables which
can be references...


But you can't get that into the curry; you've got to get it across the
create_function() interface, which means it's got to go as a string. You're
then still serialising it and so end up with a copy on the other side?

--
Andy Hassall / <an**@andyh.co.uk> / <http://www.andyh.co.uk>
<http://www.andyhsoftware.co.uk/space> Space: disk usage analysis tool
Jul 17 '05 #8
Andy Hassall wrote:
On Tue, 09 Nov 2004 23:34:36 -0800, Brion Vibber <br***@pobox.com> wrote:
Remember that you can create a callable object+method reference by
array( &$object, 'methodname' ). Objects can have member variables which
can be references...


But you can't get that into the curry; you've got to get it across the
create_function() interface, which means it's got to go as a string. You're
then still serialising it and so end up with a copy on the other side?


create_function() shouldn't be necessary; the function itself is a
pretty generic wrapper so a single class with a predefined method should
be sufficient. The bigger problem is that func_get_args() doesn't pass
through references, at least in PHP4.

-- brion vibber (brion @ pobox.com)
Jul 17 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Michael Spencer | last post by:
Wow - Alex Martelli's 'Black Magic' Pycon notes http://www.python.org/pycon/2005/papers/36/pyc05_bla_dp.pdf include this gem: > Functions 'r descriptors > def adder(x, y): return x + y > ...
3
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) {...
5
by: phil_gg04 | last post by:
Dear Javascript Experts, Opera seems to have different ideas about the visibility of Javascript functions than other browsers. For example, if I have this code: if (1==2) { function...
2
by: laredotornado | last post by:
Hello, I am looking for a cross-browser way (Firefox 1+, IE 5.5+) to have my Javascript function execute from the BODY's "onload" method, but if there is already an onload method defined, I would...
2
by: sushil | last post by:
+1 #include<stdio.h> +2 #include <stdlib.h> +3 typedef struct +4 { +5 unsigned int PID; +6 unsigned int CID; +7 } T_ID; +8 +9 typedef unsigned int (*T_HANDLER)(void); +10
8
by: Olov Johansson | last post by:
I just found out that JavaScript 1.5 (I tested this with Firefox 1.0.7 and Konqueror 3.5) has support not only for standard function definitions, function expressions (lambdas) and Function...
3
by: Beta What | last post by:
Hello, I have a question about casting a function pointer. Say I want to make a generic module (say some ADT implementation) that requires a function pointer from the 'actual/other modules'...
2
by: f rom | last post by:
----- Forwarded Message ---- From: Josiah Carlson <jcarlson@uci.edu> To: f rom <etaoinbe@yahoo.com>; wxpython-users@lists.wxwidgets.org Sent: Monday, December 4, 2006 10:03:28 PM Subject: Re: ...
2
by: Giovanni Gherdovich | last post by:
Hello, as you know the algorithm std::accumulate in the version template<class In, class T, class BinOp> T accumulate(In first, In last, T init, BinOp op) { while(first != last) init =...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.