Clojure - 如何减少功能但降低状态?

haw*_*eye 5 reduce clojure

如果我像这样使用reductions函数:

(reductions + [1 2 3 4 5])
Run Code Online (Sandbox Code Playgroud)

然后我明白了

(1 3 6 10 15)
Run Code Online (Sandbox Code Playgroud)

这很好 - 但是我想以相同的方式应用二元函数而不需要将状态转发 - 类似于

(magic-hof + [1 2 3 4 5])
Run Code Online (Sandbox Code Playgroud)

导致

(1 3 5 7 9)
Run Code Online (Sandbox Code Playgroud)

即它返回应用于第一对的操作,然后步骤1到下一对.

有人能告诉我我正在寻找的高阶函数吗?(像缩减一样)

这是我的(非工作)去吧:

(defn thisfunc [a b] [(+ a b) b])

(reduce thisfunc [1 2 3 4 5])
Run Code Online (Sandbox Code Playgroud)

Leo*_*tny 9

你可以用地图做到:

(map f coll (rest coll))
Run Code Online (Sandbox Code Playgroud)

如果你想要一个功能:

(defn map-pairwise [f coll]
  (map f coll (rest coll)))
Run Code Online (Sandbox Code Playgroud)

如果你真的需要第一个元素保持不变(thanx to juan.facorro的评论):

(defn magic-hof [f [x & xs :as s]]
  (cons x (map f s xs)))
Run Code Online (Sandbox Code Playgroud)

  • 我认为结果中缺少第一个元素:).也许`(defn magic-hof [f [x&xs:as s]](conj(map fs xs)x))`? (2认同)
  • `magic-hof`version无法正确处理空seq:`(magic-hof + [])`=>`(nil)`.但话又说回来,这取决于"正确"的含义.;) (2认同)

edb*_*ond 5

partition 将你的seq分组:

user> (->> [1 2 3 4 5] (partition 2 1) (map #(apply + %)) (cons 1))
(1 3 5 7 9)
Run Code Online (Sandbox Code Playgroud)