Clojure瞬态使用 [英] Clojure transients usage

查看:144
本文介绍了Clojure瞬态使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用clojure中的瞬变有点失落。任何帮助将不胜感激。
示例代码:

 (defn test-transient [v] 
[])]
(for [xv](conj!bx))
(persistent!b)))

user> (test-transient [1 2 3])
[]

并且结果是:

 (defn test-transient2 [v] 
(let [b [])]
(for [xv](conj!bx))
(persistent!b)
b))

user> (test-transient2 [1 2 3])
#< TransientVector clojure.lang.PersistentVector$TransientVector@1dfde20>

但是如果我使用conj!分别似乎工作确定:

 (defn test-transient3 [v] 
(let [b )]
(conj!b 0)
(conj。b 1)
(conj!b 2)
(persistent!b)))
$ b b用户> (test-transient3 [1 2 3])
[0 1 2]

有一些约束?如果是,我如何将值从持久性向量复制到瞬态?



谢谢。

解决方案

瞬态不应该像这样放在地方。



for doesn的原因是什么? 't工作是,它是懒惰和 conj!调用永远不会执行,但这是除了点,因为你不应该使用暂态的工作。 / p>

您应该使用 conj!的方式与使用regular conj



您尝试执行的操作可以这样完成:

 (defn test-transient [v] 
(let [t(transient [])]
!tv))))


I'm a bit lost with usage of transients in clojure. Any help will be appreciated. The sample code:

(defn test-transient [v]
    (let [b (transient [])]
        (for [x v] (conj! b x))
        (persistent! b)))

user> (test-transient [1 2 3])
[]

I tried to make it persistent before return and the result is:

(defn test-transient2 [v]
    (let [b (transient [])]
        (for [x v] (conj! b x))
        (persistent! b)
        b))

user> (test-transient2 [1 2 3])
#<TransientVector clojure.lang.PersistentVector$TransientVector@1dfde20>

But if I use conj! separately it seems work ok:

(defn test-transient3 [v]
    (let [b (transient [])]
    (conj! b 0)
    (conj! b 1)
    (conj! b 2)
    (persistent! b)))

user> (test-transient3 [1 2 3])
[0 1 2]

Does for has some constraint? If so, how can i copy values from persistent vector to transient?

Thank you.

解决方案

Transients aren't supposed to be bashed in-place like that. Your last example only works due to implementation details which you shouldn't rely on.

The reason why for doesn't work is that it is lazy and the conj! calls are never executed, but that is besides the point, as you shouldn't work with transients that way anyway.

You should use conj! the same way as you would use the "regular" conj with immutable vectors - by using the return value.

What you are trying to do could be accomplished like this:

(defn test-transient [v]
  (let [t (transient [])]
    (persistent! (reduce conj! t v))))

这篇关于Clojure瞬态使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆