如果我像这样使用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)
你可以用地图做到:
(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)
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)
| 归档时间: |
|
| 查看次数: |
229 次 |
| 最近记录: |