本文介绍了如何可以通过reduce来定义map,filter和reverse等操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在此博客条目中,JavaScript中的CSP和换能器 a>,作者指出:
My question is: How can operations like map, filter and reverse can be defined in terms of a reduce? Could you provide examples in Clojure?
解决方案
This is true, if we don't care about laziness. In Clojure, map
and filter
are lazy, but reduce is eager. Not only is reverse
not lazy, but the standard definition uses reduce. Modulo the laziness, we can get equivalent results for the others:
user> (defn eager-map [f coll]
(reduce (fn [acc v] (conj acc (f v)))
[]
coll))
#'user/eager-map
user> (eager-map inc (range 10))
[1 2 3 4 5 6 7 8 9 10]
user> (defn eager-filter [f coll]
(reduce (fn [acc v] (if (f v) (conj acc v) acc))
[]
coll))
#'user/eager-filter
user> (eager-filter even? (range 10))
[0 2 4 6 8]
user> (defn eager-reverse [coll]
(reduce conj () coll))
#'user/eager-reverse
user> (eager-reverse (range 10))
(9 8 7 6 5 4 3 2 1 0)
这篇关于如何可以通过reduce来定义map,filter和reverse等操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!