Curryfication de fonctions

Contenu du snippet

Nostalgiques du Caml ou d'un autre langage permettant de curryfier les fonctions ? Ne pleurez plus, voici une class PHP vous permettant de le faire !

<?php

require 'Curry.php';

$func = function($x, $y, $z) {
return $x * ($y + $z);
};

$b = new Curry($func, 2, 3);
var_dump($b(0), $b(1), $b(5));
/*
  • int(6)
  • int(8)
  • int(16)
  • /


$b = new Curry('strcmp', 'titi');
var_dump($b('toto'));
/*
  • int(-1)
  • /


?>

Source / Exemple :


<?php
// Copyright (c) 2011 Rodolphe Breard
// 
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
// 
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//

class Curry
{
  protected $nb_params;
  protected $new;

  public function __construct($func)
  {
    if (!is_callable($func))
      throw new BadMethodCallException('Curry::__construct(): invalid callback');

    $args = func_get_args();
    unset($args[0]);
    $nb_args = sizeof($args);

    if (!($func instanceof Curry))
      {
	$r = new ReflectionFunction($func);
	$this->nb_params = $r->getNumberOfRequiredParameters() - $nb_args;
      }
    else
      $this->nb_params = $func->getNbParams() - $nb_args;

    $p_lst = array();
    for ($i = 0; $i < $this->nb_params; $i++)
      $p_lst[] = '$p' . $i;

    $a_lst = array();
    for ($i = 0; $i < $nb_args; $i++)
      $a_lst[] = '$args[' . ($i + 1) . ']';
    $a_lst = array_merge($a_lst, $p_lst);

    eval('$this->new = function(' . implode(',', $p_lst) . ') use($func, $args) { return $func(' . implode(',', $a_lst) . '); };');
  }

  public function __invoke()
  {
    return call_user_func_array($this->new, func_get_args());
  }

  public function getNbParams()
  {
    return $this->nb_params;
  }
}

?>

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.