Clojure 瞬态使用 [英] Clojure transients usage

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

问题描述

我对 clojure 中瞬态的使用有点迷茫.任何帮助将不胜感激.示例代码:

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>

但是如果我使用 conj!单独看来工作正常:

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]

for 有什么限制吗?如果是这样,我如何将值从持久向量复制到瞬态?

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

谢谢.

推荐答案

瞬态不应该像那样就地攻击.您的最后一个示例仅适用于您不应该依赖的实现细节.

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.

for 不起作用的原因是它很懒惰,并且 conj! 调用永远不会被执行,但这不是重点,因为你不应该无论如何,不​​要以这种方式处理瞬态.

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.

您应该像使用带有不可变向量的常规"conj 一样使用 conj! - 通过使用返回值.

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天全站免登陆