Bad*_*ild 3 functional-programming k kdb
如何用功能性的,基于数组的语言(如K(或Q))表达这种命令性功能?
在草率的C ++中:
vector<int> x(10), y(10); // Assume these are initialized with some values.
// BTW, 4 is just a const -- it's part of the algorithm and is arbitrarily chosen.
vector<int> result1(x.size() - 4 + 1); // A place to hold a resulting array.
vector<int> result2(x.size() - 4 + 1); // A place to hold another resulting array.
// Here's the code I want to express functionally.
for (int i = 0; i <= x.size() - 4; i++) {
int best = x[i + 0] - y[i + 0];
int bad = best;
int worst = best;
for(int j = 0; j < 4; j++) {
int tmp = x[i + j] - y[i + 0];
bad = min(bad, tmp);
if(tmp > best) {
best = tmp;
worst = bad;
}
}
result1[i] = best
result2[i] = worst
}
Run Code Online (Sandbox Code Playgroud)
我最想在kdb和Q中看到这一点,但欢迎使用其他功能语言。
将@silentbicycle的k直接移植到q收益
q)a:1+til 8
q)b:8#0
q){(max x;min x)}flip{4#y _ x}[a+b;]each til count a
4 5 6 7 8 8 8 8
1 2 3 4 5 6 7 8
Run Code Online (Sandbox Code Playgroud)
另一种方法,矢量化程度更高(imao):
q){(max;min)@\:flip 4#'(til count x)_\:x+y}[a;b]
4 5 6 7 8 8 8 8
1 2 3 4 5 6 7 8
Run Code Online (Sandbox Code Playgroud)