在《七周七并发模型》中的第二天(p57),书中介绍了一个 Clojure 的 reducer 的例子,并实现了一个 my-map 函数
=> (into [] (my-map (partial * 2) (my-map (partial + 1) [1 2 3 4])))
[4 6 8 10]
其中只进行了一次化简,化简函数是 (partial * 2) 和 (partial + 1) 组合后的函数。
Reducer: REF
A reducer is the combination of a reducible collection (a collection that knows how to reduce itself) with a reducing function (the "recipe" for what needs to be done during the reduction). The standard sequence operations are replaced with new versions that do not perform the operation but merely transform the reducing function. Execution of the operations is deferred until the final reduction is performed. This removes the intermediate results and lazy evaluation seen with sequences.
如何使用 ruby 实现一个类似的函数呢?
my_map = ->(fn, arr){
# 怎么实现?
}
my_map.(->(x){x * 2}, my_map.(->(x){x + 1}, [1, 2, 3, 4])).into
# => [4, 6, 8, 10]