473,796 Members | 2,625 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2521
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($ar gs);

$lambda = sprintf(
'$args = func_get_args() ; ' .
'return call_user_func_ array(\'%s\', array_merge(uns erialize(\'%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($titl e, $obj)
{
print "$title {$obj->attr}<br>";
}

$paAttr = curry('printAtt r', '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.andyhsoftwa re.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($ar gs);

$lambda = sprintf(
'$args = func_get_args() ; ' .
'return call_user_func_ array(\'%s\', array_merge(uns erialize(\'%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($titl e, $obj)
{
print "$title {$obj->attr}<br>";
}

$paAttr = curry('printAtt r', '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.andyhsoftwa re.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.co m> 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.andyhsoftwa re.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.co m> 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
1726
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 > add23 = adder.__get__(23) > add42 = adder.__get__(42) > print add23(100), add42(1000) > 123 1042
3
14954
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) { document.images.src = eval("mt" +menu+ ".src") } alert("imgOff_hidemenu"); hideMenu=setTimeout('Hide(menu,num)',500);
5
2853
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 invisible() { alert("invisible() called"); } }
2
7681
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 like mine to run immediately after it. So in the code below, what JS would i need to add to my "myfile.inc" page so that I could guarantee this behavior? <!-- main page --> <html> <head> <script type="text/javascript">
2
12693
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
5116
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 constructors (these three I knew about), but also conditional function definitions, as described in http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Defining_Functions ]. An example: function fun() {
3
3658
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' that takes arguments of type (void *) because the ADT must be able to deal with any type of data. In my actual code, I will code the function to take arguments of their real types, then when I pass this pointer through an interface function, I...
2
5334
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: 1>make_buildinfo.obj : error LNK2019: unresolved external symbol __imp__RegQueryValueExA@24 referenced in function _make_buildinfo2 Ask on python-list@python.org . - Josiah
2
1908
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 = op(init,*first++); return init;
0
9685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9531
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10459
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10237
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10018
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9055
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5446
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3735
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2928
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.