Arithmetic.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace MathPHP\Functions;
  3. /**
  4. * Arithmetic of functions. These functions return functions themselves.
  5. */
  6. class Arithmetic
  7. {
  8. /**
  9. * Adds any number of single variable (callback) functions {f(x)}. Returns
  10. * the sum as a callback function.
  11. *
  12. * @param callable ...$args Two or more single-variable callback functions
  13. *
  14. * @return callable Sum of the input functions
  15. */
  16. public static function add(callable ...$args): callable
  17. {
  18. $sum = function ($x, ...$args) {
  19. $function = 0;
  20. foreach ($args as $arg) {
  21. $function += $arg($x);
  22. }
  23. return $function;
  24. };
  25. return function ($x) use ($args, $sum) {
  26. return $sum(...\array_merge([$x], $args));
  27. };
  28. }
  29. /**
  30. * Multiplies any number of single variable (callback) functions {f(x)}.
  31. * Returns the product as a callback function.
  32. *
  33. * @param callable ...$args Two or more single-variable callback functions
  34. *
  35. * @return callable Product of the input functions
  36. */
  37. public static function multiply(callable ...$args): callable
  38. {
  39. $product = function ($x, ...$args) {
  40. $function = 1;
  41. foreach ($args as $arg) {
  42. $function *= $arg($x);
  43. }
  44. return $function;
  45. };
  46. return function ($x) use ($args, $product) {
  47. return $product(...\array_merge([$x], $args));
  48. };
  49. }
  50. }