我如何创建一个懒惰序列向量 [英] How can I create a lazy-seq vector
问题描述
按预期运行:
(defn long-seq [n]
(lazy-seq (cons
(list n {:somekey (* n 2)})
(long-seq (+ n 1)))))
(take 3 (long-seq 3))
; => ((3 {:somekey 6}) (4 {:somekey 8}) (5 {:somekey 10}))
但是我想对向量做同样的事情:
However I would like to do the same thing with a vector:
(defn long-seq-vec [n]
(lazy-seq (into
(vector (list n {:somekey (* n 2)}))
(long-seq-vec (+ n 1)))))
(take 3 (long-seq-vec 3))
这给了我一个堆栈溢出.为什么?
This gives me a stack overflow. Why?
推荐答案
主要原因是向量不是惰性的-因此into
调用贪婪地消耗了
The main reason is that vectors aren't lazy - so the into
call greedily consumes the recursive sequences produced by long-seq-vec
and results in a stack overflow. As a corollary of this, it's not possible to create an infinite vector (in general, you can only create an infinite data structure if it is lazy or cyclic).
它在第一个示例中有效,因为cons
非常乐意在懒惰序列的前端进行懒惰行为,因此序列可以是无限的.
It works in the first example because cons
is quite happy to behave lazily when consing onto the front of a lazy sequence, so the sequence can be infinite.
假设您实际上想要向量的无限序列,那么我会提出类似的建议:
Assuming you actually want an infinite sequence of vectors I'd suggest something like:
(defn long-seq-vec [n]
(lazy-seq (cons
(vector n {:somekey (* n 2)})
(long-seq-vec (+ n 1)))))
(take 3 (long-seq-vec 3))
=> ([3 {:somekey 6}] [4 {:somekey 8}] [5 {:somekey 10}])
或者,您也可以使用本身很懒的for
:
Or as an alternative, you can use for
which is lazy in itself:
(defn long-seq-vec [n]
(for [x (iterate inc n)]
(vector x {:somekey (* x 2)})))
我更喜欢这样做,因为它避免了lazy-seq
/cons
样板,避免了递归,并且在表达函数的作用时更加清晰了……如果您愿意,它更声明式".您也可以类似的方式使用map
.
I prefer this as it avoids the lazy-seq
/cons
boilerplate, avoids recursion and is slightly more clear in expressing what your function does... it's a little more "declarative" if you like. You could also use map
in a similar way.
这篇关于我如何创建一个懒惰序列向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!