简体   繁体   English

assoc行为是否不一致?

[英]Is assoc behavior inconsistent?

assoc may throw IndexOutOfBoundsException when the index is, well, out of bounds, as in: 当索引超出范围时, assoc可能抛出IndexOutOfBoundsException,如:

user=> (assoc [] 1 nil)
IndexOutOfBoundsException   clojure.lang.PersistentVector.assocN(PersistentVector.java:137)

Why wouldn't it throw that same exception if I try to set the value at index 0? 如果我尝试在索引0处设置值,为什么不会抛出相同的异常呢?

user=> (assoc [] 0 nil)
[nil]

It seems to me that in both cases the index is out of bounds ... 在我看来,在这两种情况下,指数都超出界限......

Thanks 谢谢

Assoc-in uses assoc to modify the element at the supplied key (index in your case). Assoc-in使用assoc来修改所提供键的元素(在您的情况下为索引)。 Assoc-in (and assoc) try to create what keys (or indexes) you require. Assoc-in(和assoc)尝试创建所需的键(或索引)。

The special treatment for vectors is mentioned in the assoc docstring: 关联向量的特殊处理在assoc docstring中提到:

When applied to a vector, returns a new vector that contains val at index. 应用于向量时,返回包含val的索引的新向量。 Note - index must be <= (count vector) . 注 - 索引必须是<=(计数向量)

Update: Just to clarify: The missing exception is consistent because while 0 is a valid index for a new element in an empty vector, 1 is not. 更新:只是为了澄清:缺少的异常是一致的,因为0是空向量中新元素的有效索引,而1不是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM