如何用像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
}
我最希望在kdb和 Q 中看到这一点,但欢迎使用其他函数式语言。