Clojure:用三个参数减少 [英] Clojure: reduce with three parameters
问题描述
我经常发现自己需要一种扩展 reduce
,每当我必须处理一个项目时(如reduce),累积某种结果(如reduce)但是基于序列的前一项执行该过程(不像reduce)。
I often find myself in need of a kind of expanded reduce
whenever I must process an item at time (like reduce), accumulate some kind of result (like reduce) but do the process based on the previous item of the sequence (unlike reduce).
例如(一个愚蠢的),如果当前项而前一个是偶数,减去它们中的一个是奇数。这只是一个蠢的例子,但我经常遇到这种问题。我通常做一个向量作为累加器,使第一个项目是真正的聚合,第二个是前一项。这不是很优雅,而且很冗长。
For example (a silly one), add 1 to the accumulator if both the current item and the previous one are even and subtract one of they're odd. This is just a stupid case, but I've run into this kind of problems often. I generally make a vector as accumulator, so that the first item is the real aggregation and the second one is the previous item. This is not very elegant and certainly verbose.
在这些情况下有帮助的核心功能吗?什么是最常用的方式来处理这样的问题?感谢
Is there a core function to help in those cases? What is the most idiomatic way to deal with such problem? Thanks
推荐答案
分区
$ b
partition
to the rescue.
(reduce (fn [i [a b]]
(cond
(and (even? a) (even? b)) (inc i)
(and (odd? a) (odd? b)) (dec i)
:else i))
0 (partition 2 1 input))
或更简洁一些:
(reduce (fn [i pair]
(condp every? pair
even? (inc i)
odd? (dec i)
i))
0 (partition 2 1 input))
这篇关于Clojure:用三个参数减少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!