ListOps.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /*
  3. * By adding type hints and enabling strict type checking, code can become
  4. * easier to read, self-documenting and reduce the number of potential bugs.
  5. * By default, type declarations are non-strict, which means they will attempt
  6. * to change the original type to match the type specified by the
  7. * type-declaration.
  8. *
  9. * In other words, if you pass a string to a function requiring a float,
  10. * it will attempt to convert the string value to a float.
  11. *
  12. * To enable strict mode, a single declare directive must be placed at the top
  13. * of the file.
  14. * This means that the strictness of typing is configured on a per-file basis.
  15. * This directive not only affects the type declarations of parameters, but also
  16. * a function's return type.
  17. *
  18. * For more info review the Concept on strict type checking in the PHP track
  19. * <link>.
  20. *
  21. * To disable strict typing, comment out the directive below.
  22. */
  23. declare(strict_types=1);
  24. class ListOps {
  25. public function append(array $list1, array $list2): array {
  26. $list = $list1;
  27. foreach ($list2 as $item) {
  28. $list[] = $item;
  29. }
  30. return $list;
  31. }
  32. public function concat(array $list1, array ...$listn): array {
  33. $res = $list1;
  34. foreach ($listn as $list) {
  35. foreach ($list as $item) {
  36. $res[] = $item;
  37. }
  38. }
  39. return $res;
  40. }
  41. /**
  42. * @param callable(mixed $item): bool $predicate
  43. */
  44. public function filter(callable $predicate, array $list): array {
  45. return array_values(array_filter($list, $predicate));
  46. }
  47. public function length(array $list): int {
  48. return count($list);
  49. }
  50. /**
  51. * @param callable(mixed $item): mixed $function
  52. */
  53. public function map(callable $function, array $list): array {
  54. return array_map($function, $list);
  55. }
  56. /**
  57. * @param callable(mixed $accumulator, mixed $item): mixed $function
  58. */
  59. public function foldl(callable $function, array $list, $accumulator) {
  60. return array_reduce($list, $function, $accumulator);
  61. }
  62. /**
  63. * @param callable(mixed $accumulator, mixed $item): mixed $function
  64. */
  65. public function foldr(callable $function, array $list, $accumulator) {
  66. return array_reduce(array_reverse($list), $function, $accumulator);
  67. }
  68. public function reverse(array $list): array {
  69. return array_reverse($list);
  70. }
  71. }