【发布时间】:2019-09-29 02:34:07
【问题描述】:
我正在阅读七周内的七个并发模型,并且没有关于 Clojure 的先验知识。我很难理解下面的代码,它在集合上实现了 map 函数(可简化)。
我已将我的具体问题放在代码正文中,但我对代码逻辑更感兴趣。我知道 coll-reduce 是为一堆序列对象定义的,但是在这段代码中如何使用它来实现 map 让我很困惑。
感谢任何提示。
;---
; Excerpted from "Seven Concurrency Models in Seven Weeks",
; published by The Pragmatic Bookshelf.
; Copyrights apply to this code. It may not be used to create training material,
; courses, books, articles, and the like. Contact us if you are in doubt.
; We make no guarantees that this code is fit for any purpose.
; Visit http://www.pragmaticprogrammer.com/titles/pb7con for more book information.
;---
(ns reducers.core
(:require [clojure.core.protocols :refer [CollReduce coll-reduce]]
[clojure.core.reducers :refer [CollFold coll-fold]]))
(defn make-reducer [reducible transformf]
(reify
CollReduce
(coll-reduce [_ f1]
(coll-reduce reducible (transformf f1) (f1))) ; what's the meaning of (f1) here?
(coll-reduce [_ f1 init]
(coll-reduce reducible (transformf f1) init))))
(defn my-map [mapf reducible]
(make-reducer reducible
(fn [reducef]
(fn [acc v]
(reducef acc (mapf v))))))
(into [] (my-map (partial * 2) [1 2 3 4])) ; I don't really understand what's reducef and what's acc here
【问题讨论】:
标签: clojure