简体   繁体   English

Clojure减少需要val参数来累积向量

[英]Clojure reduce requires val parameter to accumulate vector

I am doing a reduce where I want to accumulate and return a vector. 我正在做一个减少要累积并返回向量的地方。 It works fine when done like this: 像这样完成时,它可以正常工作:

(reduce
  (fn [[res-vec last-rgb] rgb]
    (let [calc-res (mu/colour-distance-L2 last-rgb rgb)
          accum-results (conj res-vec calc-res)]
      [accum-results rgb]))
  []
  colour-selections)

However when the [] parameter is left out I get Caused by: java.lang.IllegalArgumentException: Don't know how to create ISeq from: java.lang.Long . 但是,当[]参数被忽略时,我会Caused by: java.lang.IllegalArgumentException: Don't know how to create ISeq from: java.lang.Long This occurs because colour-distance-L2 is being given at least one java.lang.Long rather than two vectors as it expects (both vectors of the type [rgb] - for red green and blue). 发生这种情况的原因是,给了colour-distance-L2至少一个java.lang.Long而不是预期的两个向量( [rgb] 类型的两个向量-红色,绿色和蓝色)。

This is exactly the kind of reduce I am doing. 正是我正在做的减少。

I do not need to use the 3-arity version of reduce, because colour-selections will always have a size of at least 2. I just put the [] as part of the trial and error of getting past the run-time error. 我不需要使用reduce的3-arity版本,因为colour-selections将始终具有至少2的大小。我只是将[]作为克服运行时错误的反复试验的一部分。 And as it turns out doing this somehow has a good effect. 事实证明,这样做具有良好的效果。

Is there some way I can use the 2-arity version of reduce here? 有什么办法可以在这里使用reduce的2-arity版本?

You can only use 2-arity reduce provided your reducing function has a signature like (A,A) → A - taking two values of the same type and producing another value of that type. 您只能使用2-arityreduce,前提是您的reduce函数具有(A,A)→A之类的签名-接受两个相同类型的值并产生该类型的另一个值。
Yours has a signature of (A,B) → A, where A is a pair [res-vec last-rgb] 您的签名为(A,B)→A,其中A是一对[res-vec last-rgb]
and B is a triple [rgb] . B是三元组[rgb] If you want to reduce it over a sequence of B, providing the first A to start the sequence is necessary , because the function doesn't know how to make two Bs into an A. 如果要通过B序列来减少它, 则必须提供第一个A来开始序列,因为该函数不知道如何将两个B变成A。

That being said, I'm not quite seeing the need for a reduce here. 话虽这么说,但我不太明白在这里需要reduce Assuming res-vec is the interesting value from your reduction it could also be produced by mapping colour-distance over colour-selections and itself less 1 element. 假设res-vec是从还原有趣值它也可以通过映射的颜色距离过度产生colour-selections和本身少1个元素。 Something like 就像是

(mapv mu/colour-distance-L2 colour-selections (drop 1 colour-selections))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM