-
Notifications
You must be signed in to change notification settings - Fork 0
/
fo-curry.php
95 lines (69 loc) · 1.52 KB
/
fo-curry.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
/** CURRY */
/**
* 未指定$fn怎样使用$data, 硬化了入参顺序
* 还是硬化编码
*
* @param function $fn 主要实现逻辑的函数
* @param mixed $data 数据 预加载数据
* @return function 得到一个扩展函数
*/
function curry($fn, $data)
{
return function ($argv) use ($data, $fn) {
return $fn($data, $argv);
};
}
// 一次性 curry
// $increment = function ($n) {
// return add(1, $n);
// };
$increment = curry('add', 1);
echo $increment(1);
echo $increment($increment($increment(3)));
function map($fn, $a)
{
$newA = array();
foreach ($a as $key => $val) {
$newA[] = $fn($val, $key);
}
return $newA;
}
$love = array(
'I' => 'me',
'Love' => 'miss',
'You' => 'aar',
);
$tell = function($val, $key){
echo $key, ' => ', $val, "\n";
};
map($tell, $love);
$increment = curry('map', function($val, $key) use ($tell) {
$val .= ' more';
$tell($val, $key);
});
$increment($love);
// ***************************
// NEW CURRY (For me)
// ***************************
function newCurry($fn, $data)
{
return function ($argv) use ($data, $fn) {
return $fn();
};
}
/** demo 1: */
$match = newCurry(function($match, $data){
preg_match($match, $data, $results);
return $results;
}, '/\s+/');
// $match('/\s+/')('hello, world');
/** demo 2: */
function add($a, $b)
{
return $a + $b;
}
$curriedAdd = newCurry(function($increment, $data){
return add($increment, $data);
}, 1);
// echo $curriedAdd(0)(1);