reduce (:T)
语法
reduce(func, X, [init], [consistent=false])
或
[init] <operator>:T X (表示 consistent 为 false)
或
[init] <operator>:TC X (表示 consistent 为 true)
New in version 1.30.21.
或
reduce:T(X, [init], [consistent=false])
参数
func 函数。
当 func 是一元函数时,X 可以是非负整数、一元函数或空值。init 表示 func 的参数,必须指定。
func 是二元函数时,X 是向量、矩阵或表。init 表示初始值。
func 是三元函数时,X 必须是一个 Tuple,包含2个元素,分别表示 func 的后两个参数。
consistent 布尔值,默认 false,表示每个子任务输出的数据类型由实际计算结果决定。否则,每个子任务输出的数据类型将与第一个子任务输出的数据类型保持一致。 请注意,当前版本的实现不受 consistent 参数的影响,即 consistent 设置无效。
详情
该函数与 accumulate 的功能相同,唯一区别是返回值不同。reduce 返回最后一个结果,而 accumulate 输出所有中间结果。关于函数功能描述,参见 accumulate (:A)。
reduce 等同于下面的伪代码的执行过程:
result=<function>(init,X[0]);
for(i:1~size(X)){
result=<function>(result, X[i]);
}
return result;
例子
func 是一元函数时:
//定义一个一元函数
$ def func1(x){
$ if(x<5){
$ return x*3
$ }
$ else{
$ return x+3
$ }
$ }
//当 X 为整数时,迭代 X 次,输出最后一个结果
$ reduce(func1, 5, 1)
18
//当 X 为一元函数 condition 时,第3次迭代时因 condition 返回false,停止迭代2次后停止,并输出最后一个结果。
$ def condition(x){
$ return x<9
}
$ reduce(func1, condition, 1)
9
//当 X 为 NULL(或不指定)时,自定义函数 func2 作为进行迭代的函数。
$ def func2(x){
$ if(x<5){
$ return x*3
$ }
$ else{
$ return 6
$ }
$ }
//因第4次迭代结果和第3次相同,停止迭代并输出最后一个结果。
$ reduce(func2,NULL,1)
6
func 是二元函数时,在一个向量上执行 reduce:
$ reduce(mul, 1..10);
3628800
// 10的阶乘
// 上例相应的accumulate 高阶函数实现。
$ *:A 1..10;
[1,2,6,24,120,720,5040,40320,362880,3628800]
$ 2 *:T 1..10;
7257600
$ def f1(a,b):a+log(b);
$ reduce(f1, 1..5, 0);
4.787492
对一个矩阵执行 reduce:
$ x=1..12$3:4;
$ x;
col1 |
col2 |
col3 |
col4 |
---|---|---|---|
1 |
4 |
7 |
10 |
2 |
5 |
8 |
11 |
3 |
6 |
9 |
12 |
$ + :T x;
[22,26,30]
func 是三元函数时:
$ def fun3(x,y,z){
$ return x+y+z
$ }
$ reduce(fun3,[[1,2,3],[10,10,10]],5)
41