```Clojure: 转换器```
Clojure: Transducers

原始链接: https://clojure.org/reference/transducers

## Clojure 中的转换器:总结 转换器是具有特定形状 `(fn [rf] (fn ([] ...) ([result] ...) ([result input] ...)))` 的函数,用于构建可组合的序列转换。 核心序列函数,如 `map` 和 `filter`,返回转换器,并闭包其参数(谓词、函数等)。 这些转换器利用三种元数:**初始化**(启动过程)、**步骤**(执行核心转换,可能多次调用嵌套的 `rf`)和 **完成**(完成过程,刷新状态)。 转换器通过 `reduced` 支持 **提前终止**,要求步骤函数检查并传播此信号。 一些转换器需要 **归约状态**(如 `dedupe`),在转换器的上下文中进行管理,使用诸如 `volatile!` 或 `atom!` 之类的结构。 此状态在过程开始时初始化,并在完成时刷新,除非提前终止。 本质上,转换器提供了一种强大而高效的方式来定义和组合 Clojure 中的数据转换,将状态和控制流封装在函数式框架中。

Hacker News 新闻 | 过去 | 评论 | 提问 | 展示 | 招聘 | 提交 登录 Clojure: Transducers (clojure.org) 9 分,by tosh 1小时前 | 隐藏 | 过去 | 收藏 | 1 评论 帮助 mannycalavera42 15分钟前 [–] transducers 和异步流程 :chefkiss 回复 考虑申请YC 2026年夏季批次!申请截止至5月4日 指南 | 常见问题 | 列表 | API | 安全 | 法律 | 申请YC | 联系 搜索:
相关文章

原文

Transducers have the following shape (custom code in "…​"):

(fn [rf]
  (fn ([] ...)
      ([result] ...)
      ([result input] ...)))

Many of the core sequence functions (like map, filter, etc) take operation-specific arguments (a predicate, function, count, etc) and return a transducer of this shape closing over those arguments. In some cases, like cat, the core function is a transducer function and does not take an rf.

The inner function is defined with 3 arities used for different purposes:

  • Init (arity 0) - should call the init arity on the nested transform rf, which will eventually call out to the transducing process.

  • Step (arity 2) - this is a standard reduction function but it is expected to call the rf step arity 0 or more times as appropriate in the transducer. For example, filter will choose (based on the predicate) whether to call rf or not. map will always call it exactly once. cat may call it many times depending on the inputs.

  • Completion (arity 1) - some processes will not end, but for those that do (like transduce), the completion arity is used to produce a final value and/or flush state. This arity must call the rf completion arity exactly once.

An example use of completion is partition-all, which must flush any remaining elements at the end of the input. The completing function can be used to convert a reducing function to a transducing function by adding a default completion arity.

Early termination

Clojure has a mechanism for specifying early termination of a reduce:

  • reduced - takes a value and returns a reduced value indicating reduction should stop

  • reduced? - returns true if the value was created with reduced

  • deref or @ can be used to retrieve the value inside a reduced

A process that uses transducers must check for and stop when the step function returns a reduced value (more on that in Creating Transducible Processes). Additionally, a transducer step function that uses a nested reduce must check for and convey reduced values when they are encountered. (See the implementation of cat for an example.)

联系我们 contact @ memedata.com