Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 93 lines (81 sloc) 2.38 kb
4b0e394 @jaz303 Added build target for PHP 5.3 specific functions
authored
1 <?php
578fac6 @jaz303 added functional primitives
authored
2 //
3 // Functional programming primitives
4
5 // returns the arity of the given closure
6 function arity($lambda) {
7 $r = new ReflectionObject($lambda);
8 $m = $r->getMethod('__invoke');
9 return $m->getNumberOfParameters();
10 }
11
12 function every($iterable, $lambda) {
13 if (arity($lambda) < 2) {
14 foreach ($iterable as $i) $lambda($i);
15 } else {
16 foreach ($iterable as $k => $v) $lambda($k, $v);
17 }
18 }
19
20 function every_with_index($iterable, $lambda) {
21 $c = 0;
22 if (arity($lambda) < 3) {
23 foreach ($iterable as $i) $lambda($i, $c++);
24 } else {
25 foreach ($iterable as $k => $v) $lambda($k, $v, $c++);
26 }
27 }
28
29 function map($iterable, $lambda) {
30 $out = array();
31 foreach ($iterable as $v) $out[] = $lambda($v);
32 return $out;
33 }
34
35 function kmap($iterable, $lambda) {
36 $out = array();
37 foreach ($iterable as $k => $v) $out[$k] = $lambda($v);
38 return $out;
39 }
40
41 // returns true iff $lambda($v) returns true for all values $v in $iterable
42 function all($iterable, $lambda) {
43 foreach ($iterable as $v) {
44 if (!$lambda($v)) return false;
45 }
46 return true;
47 }
48
49 // returns true iff $lambda($v) returns true for any value $v in $iterable
50 function any($iterable, $lambda) {
51 foreach ($iterable as $v) {
52 if ($lambda($v)) return true;
53 }
54 return false;
55 }
56
57 function inject($iterable, $memo, $lambda) {
58 if (arity($lambda) < 3) {
59 foreach ($iterable as $v) $memo = $lambda($memo, $v);
60 } else {
61 foreach ($iterable as $k => $v) $memo = $lambda($memo, $k, $v);
62 }
63 return $memo;
64 }
65
66 // filters $iterable, returning only those values for which $lambda($v) is true
67 function filter($iterable, $lambda) {
68 $out = array();
69 foreach ($iterable as $v) if ($lambda($v)) $out[] = $v;
70 return $out;
71 }
72
73 // as filter(), but preserves keys
74 function kfilter($iterable, $lambda) {
75 $out = array();
76 foreach ($iterable as $k => $v) if ($lambda($v)) $out[$k] = $v;
77 return $out;
78 }
79
80 // filters $iterable, removing those values for which $lambda($v) is true
81 function reject($iterable, $lambda) {
82 $out = array();
83 foreach ($iterable as $v) if (!$lambda($v)) $out[] = $v;
84 return $out;
85 }
86
87 // as reject(), but preserves keys
88 function kreject($iterable, $lambda) {
89 $out = array();
90 foreach ($iterable as $k => $v) if (!$lambda($v)) $out[$k] = $v;
91 return $out;
92 }
4b0e394 @jaz303 Added build target for PHP 5.3 specific functions
authored
93 ?>
Something went wrong with that request. Please try again.