gpt4 book ai didi

clojure - 序列对换能器有什么作用?

转载 作者:行者123 更新时间:2023-12-02 03:11:51 25 4
gpt4 key购买 nike

关于sequence的两个相关问题:

给定一个换能器,例如(def xf (comp (filter odd?) (map inc))),

  1. (into [] xf (range 10))(into () xf (range 10))有什么关系(序列 xf(范围 10))?是否只是没有惰性序列的语法可以用作 into 的第二个参数,所以我们需要一个单独的函数 sequence 来实现这个目的? (我知道 sequence 还有另一种非换能器用途,将集合强制转换为一种或另一种序列。)

  2. Clojure transducers page说,关于 sequence 的使用,就像上面的那样,

The resulting sequence elements are incrementally computed. These sequences will consume input incrementally as needed and fully realize intermediate operations. This behavior differs from the equivalent operations on lazy sequences.

对我来说,这听起来好像 sequence 没有返回一个惰性序列,但是 sequence 的文档字符串说“当提供一个传感器时,返回一个惰性序列将转换应用到 coll(s) 中的项目,...”,实际上 (class (sequence xf (range 10))) 返回 clojure.lang.LazySeq。我想我不明白上面从 Clojure 转换器页面引用的最后一句话。

最佳答案

(sequence xform from)TransformerIterator 上创建 lazy-seq (RT.chunkIteratorSeq) < em>xform 和 from 被传递。当请求下一个值时,xform(转换的组合)被调用以覆盖 from 的下一个值。

This behavior differs from the equivalent operations on lazy sequences.

惰性序列的等效操作是什么?以你的 xf 为例,将 filter odd? 应用于 (range 10),生成中间惰性序列,并将 map inc 应用于中间惰性序列,生成最终惰性序列为结果。

我会说 (into to xform from) 类似于 (into to (sequence xform from))from 是一些未实现 IReduceInit 的集合。

into 内部使用 (transduce xform conj to from) 做与 (reduce (xform conj) to from) 相同,最后 clojure.core.protocols/coll-reduce 被调用:

(into [] (sequence xf (range 10)))
;[2 4 6 8 10]
(into [] xf (range 10))
;[2 4 6 8 10]
(transduce xf conj [] (range 10))
;[2 4 6 8 10]
(reduce (xf conj) [] (range 10))
;[2 4 6 8 10]

我将你的转换器稍微修改成:

(defn hof-pr
"Prints char c on each invocation of function f within higher order function"
([hof f c]
(hof (fn [e] (print c) (f e))))
([hof f c coll]
(hof (fn [e] (print c) (f e)) coll)))
(def map-inc-pr (partial hof-pr map inc \m))
(def filter-odd-pr (partial hof-pr filter odd? \f))
(def xf (comp (filter-odd-pr) (map-inc-pr)))

以便它在每个转换步骤中打印出字符。

在 REPL 中创建 s1 如下:

(def s1 (into [] xf (range 10)))
ffmffmffmffmffm

s1 被急切地评估(打印 f 用于过滤,m 用于映射)。再次请求 s1 时没有评估:

s1
[2 4 6 8 10]

让我们创建s2:

(def s2 (sequence xf (range 10)))
ffm

仅评估 s2 中的第一项。将在请求时评估下一个项目:

s2
ffmffmffmffm(2 4 6 8 10)

另外,以旧方式创建 s3:

(def s3 (map-inc-pr (filter-odd-pr (range 10))))
s3
ffffffffffmmmmm(2 4 6 8 10)

如您所见,定义s3 时没有评估。当请求 s3 时,应用过滤 10 个元素,然后应用剩余 5 个元素的映射,生成最终序列。

关于clojure - 序列对换能器有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39566041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com