eachPre
Syntax
eachPre(func, X, [pre], [consistent=false])
or
[pre] <operator>:P X
(when consistent = false)
or
[pre] <operator>:PC X
(when consistent = true)
or
func:P([pre], X)
(when consistent = false)
or
func:PC([pre], X)
(when consistent = true)
Arguments
func is a binary function.
X is a vector/matrix/table. When X is a matrix, pre must be a scalar or vector; when X is a table, pre must be a scalar or table. When pre is absent, the first element in the result would be NULL.
consistent is a Boolean value. The default value is false, indicating that the data type of the result is determined by each calculation result. Otherwise, the data type of the result is the same as the data type of the first calculation result. Note that if the data forms of result are inconsistent, consistent can only be specified as false. Otherwise, an error will be reported.
Details
Apply func over all pairs of consecutive elements of X. It is
equivalent to: F(X[0], pre), F(X[1], X[0]), ..., F(X[n],
X[n-1])
.
The built-in functions ratios and deltas are also implemented by the
eachPre
template. They are defined as:
-
function deltas(a){return a[0] -:P a}
-
function ratios(a){return a[0] :P a}
Examples
x=1..10;
eachPre(sub, x);
// output
[,1,1,1,1,1,1,1,1,1]
// equivalent to [NULL, 2-1, ..., 10-9]
-:P x;
// output
[,1,1,1,1,1,1,1,1,1]
// same as above
eachPre(+, x);
// output
[,3,5,7,9,11,13,15,17,19]
// equivalent to [NULL, 2+1, ..., ]
0 +:P x;
// output
[1,3,5,7,9,11,13,15,17,19]
// equivalent to [1+0, 2+1, ..., ]
x=1..12$3:4;
// output
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)
// output
([6],8,12)