Function arity of a first-class function

519 views Asked by At

I'm rewriting PHP type system and working on implementation of a more pure language. I'm implementing as much as I can in question of purism as functional and object-oriented language, like method-chaining, types as objects, message-passing, conditionals as methods and some other features http://github.com/haskellcamargo/rawr. In this, functions will be instance of Func class and after I'll do a transcompiler for it, because PHP has gone so far as it is. Func will not limit to unary functions as parameters, but will check if, when called, the number of arguments matches exactly the number of expected arguments:

$add = Func(function(Number $x) {
  return Func(function(Number $y) use ($x) {
    return $x -> add ($y);
  });
});

Where add will be a function where I don't need to control its arity, as much as it is unary and works by currying. But when I work with functions that receive multiple parameters, my problem appears. Let's take as example a simple function that outputs a name in the screen:

$say_name = Func(function(String $name) {
  $name -> outputln();
});

$say_name requires 1 unique parameter but how can I assert that it will receive n parameters, being n the arity of this anonymous function?

$say_name -> invoke("Test"); might work, but $say_name -> invoke("Test", 1); also works because I'm not getting a way to know the arity of a anonymous function.

function () { return func_num_args(); }

This will return the number of arguments passed to it. I need to know the number of required arguments to x, something like:

function x(Int $i, Functor $j) { return a_magic_function_that_returns_it_all(); }

And outputs me something like array(2) { [0]=> Int [1]=> Functor }. Can somebody help me with that?

1

There are 1 answers

0
Marcelo Camargo On BEST ANSWER

Solved with usage of ReflectionFunction:

 $add = function($x, $y) { return $x + $y; };
 $x = new ReflectionFunction($add);
 $args = $x->getParameters();
 var_dump(count($args)); // 2