Currying a function

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Rico Huijbers

    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
  • Brandon Blackmoor

    #2
    Re: Currying a function

    Rico Huijbers wrote:[color=blue]
    >
    > I'd like to know if it's possible to curry a function in PHP?[/color]

    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):



    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

    Comment

    • Phil Roberts

      #3
      Re: Currying a function

      Rico Huijbers <E.A.M.Huijbers @REMOVEstudent. tue.nl> treated the
      lovely people of comp.lang.php with the following stuff:
      [color=blue]
      > 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?
      >[/color]

      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.

      Comment

      • Andy Hassall

        #4
        Re: Currying a function

        On Tue, 09 Nov 2004 16:47:30 +0100, Rico Huijbers
        <E.A.M.Huijbers @REMOVEstudent. tue.nl> wrote:
        [color=blue]
        >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?[/color]

        Not built in.
        [color=blue]
        >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'[/color]

        Looks like a good start.
        [color=blue]
        >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)?[/color]

        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 / <andy@andyh.co. uk> / <http://www.andyh.co.uk >
        <http://www.andyhsoftwa re.co.uk/space> Space: disk usage analysis tool

        Comment

        • Rico Huijbers

          #5
          Re: Currying a function

          Andy Hassall wrote:[color=blue]
          > 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
          > ?>
          >[/color]

          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

          Comment

          • Andy Hassall

            #6
            Re: Currying a function

            On Wed, 10 Nov 2004 00:06:56 +0100, Rico Huijbers
            <E.A.M.Huijbers @REMOVEstudent. tue.nl> wrote:
            [color=blue]
            >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.[/color]

            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 / <andy@andyh.co. uk> / <http://www.andyh.co.uk >
            <http://www.andyhsoftwa re.co.uk/space> Space: disk usage analysis tool

            Comment

            • Brion Vibber

              #7
              Re: Currying a function

              Andy Hassall wrote:[color=blue]
              > 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* :-)[/color]

              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)

              Comment

              • Andy Hassall

                #8
                Re: Currying a function

                On Tue, 09 Nov 2004 23:34:36 -0800, Brion Vibber <brion@pobox.co m> wrote:
                [color=blue]
                >Andy Hassall wrote:[color=green]
                >> 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* :-)[/color]
                >
                >Remember that you can create a callable object+method reference by
                >array( &$object, 'methodname' ). Objects can have member variables which
                >can be references...[/color]

                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 / <andy@andyh.co. uk> / <http://www.andyh.co.uk >
                <http://www.andyhsoftwa re.co.uk/space> Space: disk usage analysis tool

                Comment

                • Brion Vibber

                  #9
                  Re: Currying a function

                  Andy Hassall wrote:[color=blue]
                  > On Tue, 09 Nov 2004 23:34:36 -0800, Brion Vibber <brion@pobox.co m> wrote:[color=green]
                  >>Remember that you can create a callable object+method reference by
                  >>array( &$object, 'methodname' ). Objects can have member variables which
                  >>can be references...[/color]
                  >
                  > 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?[/color]

                  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)

                  Comment

                  Working...