Numbers\root()

transformer returns Closure pure throws
number → (number → number)
At a glance — Bind a root index (2 for square root, 3 for cube root, etc.); the returned Closure computes pow(value, 1/root). Throws InvalidArgumentException on non-number input.

Creates a Closure that takes the pre-defined nth root of any number passed to it. Implemented as `pow($value, 1 / $root)` — root of 2 gives you the square root, root of 3 the cube root, and so on.

/**
  * @param int|float $root The root index — 2 for square root, 3 for cube root, etc.
  * @return Closure(int|float):(int|float)
  * @throws InvalidArgumentException If $root is not int or float.
  */
Numbers\root($root): Closure

Returned Closure

When Numbers\root() is called, it returns the following Closure which can be used like a regular function.

/**
  * @param int|float $value
  * @return int|float  Result of pow($value, 1 / $root).
  * @throws InvalidArgumentException If $value is not int or float.
  */
$function (int|float $value): int|float

Examples

Partial Application

This can be used to create a simple closure which can be used as a regular function.

// Create a square root function.
$sqrt = Numbers\root(2);

// Called as a function.
echo $sqrt(16); // 4.0
echo $sqrt(25); // 5.0
echo $sqrt(2);  // 1.4142135623731

// Used in a higher order function.
$array = array_map($sqrt, [1, 4, 9, 16, 25]);
print_r($array); // [1.0, 2.0, 3.0, 4.0, 5.0]

Curried

This can be called inline using currying.

echo Numbers\root(3)(27); // 3.0

Inlined with Higher Order Function

If you are not planning on reusing the Closure created, you can just call it inline with a higher order function as its callable.

$cubeRoots = array_map(Numbers\root(3), [1, 8, 27, 64]);
print_r($cubeRoots); // [1.0, 2.0, 3.0, 4.0]

Details

Numbers Functions

Releated Number transform Functions