3

如何用像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 中看到这一点,但欢迎使用其他函数式语言。

4

3 回答 3

5

将@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

另一种方法,稍微矢量化(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
于 2012-03-23T02:39:19.797 回答
4

Kona(一种开源的 K 方言)中:

首先,设置一些示例值(使用与 Clojure 解决方案相同的方法):

a:1+!8;b:8#0        / a is 1..8, b is eight 0s

然后:

{(|/x;&/x)}@+{4#y _ x}[a+b;]'!#a

其中ab是上面的 x 和 y 变量。(K 对变量 x、y 和 z 进行了特殊处理。)

再细分一下:

maxmin:{(|/x;&/x)}  / (max;min) pairs of x
get4:{4#y _ x}      / next 4 from x, starting at y
                    / with <4 remaining, will repeat; doesn't matter for min or max
/ maxmin applied to flipped results of get4(a-b) at each index 0..(length a)-1
maxmin@+get4[a-b;]'!#a

/ result
(4 5 6 7 8 8 8 8
 1 2 3 4 5 6 7 8)
于 2011-07-23T14:13:33.170 回答
1

ClojureLisp的一种方言)中:

(defn minmax [x y](map #(vector (- (apply max %1) %2) (- (apply min %1) %2)))(partition-all 4 1 x) y)

(minmax [1 2 3 4 5 6 7 8] [0 0 0 0 0 0 0 0])

会给

[([4 1] [5 2] [6 3] [7 4] [8 5] [8 6] [8 7] [8 8])`(结果1,结果2)作为输出..

然后

(map #(first %1) result) is result1
(map #(last %1) result) is result2
于 2011-07-20T01:52:11.493 回答