eachPre (:P)
语法
eachPre(func, X, [pre], [consistent=false])
或
[pre] <operator>:P X (表示 consistent 为 false)
或
[pre] <operator>:PC X(表示 consistent 为 true)
New in version 1.30.21.
或
func:P(X, [pre], [consistent=false])
参数
func 是一个二元函数。
X 可以是向量、矩阵或表。当X是向量时,pre必须是标量;当X是矩阵时,pre必须是标量或向量;当X是表时,pre必须是标量或表;当pre未指定时,结果的第一个元素为NULL。
consistent 布尔值,默认 false,表示每个子任务输出的数据类型由实际计算结果决定。否则,每个子任务输出的数据类型将与第一个子任务输出的数据类型保持一致。 注意,若子任务输出的数据形式不一致,只能指定 consistent = false,否则会报错。
详情
将给定函数/运算符应用于X中所有相邻的数据对。
eachPre 高阶函数等同于: F(X[0], pre), F(X[1], X[0]), …, F(X[n], X[n-1])。
内置函数 ratios 和 deltas 也是通过用 eachPre 高阶函数实现。定义如下:
function deltas(a){return a[0] -:P a}
function ratios(a){return a[0] :P a}
例子
$ x=1..10;
$ eachPre(sub, x);
[,1,1,1,1,1,1,1,1,1]
// 等同于[NULL, 2-1, ..., 10-9]
$ -:P x;
[,1,1,1,1,1,1,1,1,1]
// 同上
$ eachPre(+, x);
[,3,5,7,9,11,13,15,17,19]
// 等同于 [NULL, 2+1, ..., ]
$ 0 +:P x;
[1,3,5,7,9,11,13,15,17,19]
// 等同于 [1+0, 2+1, ..., ]
$ x=1..12$3:4;
x;
col1 |
col2 |
col3 |
col4 |
---|---|---|---|
1 |
4 |
7 |
10 |
2 |
5 |
8 |
11 |
3 |
6 |
9 |
12 |
$ - :P x;
col1 |
col2 |
col3 |
col4 |
---|---|---|---|
3 |
3 |
3 |
|
3 |
3 |
3 |
|
3 |
3 |
3 |
$ eachPre(\, x, x[0]);
col1 |
col2 |
col3 |
col4 |
---|---|---|---|
1 |
4 |
1.75 |
1.428571 |
1 |
2.5 |
1.6 |
1.375 |
1 |
2 |
1.5 |
1.333333 |
$ def f1(a,b){
$ return (a[`x])+(a[`y])+(b[`x])+(b[`y])
$ }
$ t = table(1 2 3 as x,2 3 4 as y)
$ t1 = table(1 as x,2 as y)
$ eachPre(f1,t,t1)
([6],8,12)