简体   繁体   中英

Is assoc behavior inconsistent?

assoc may throw IndexOutOfBoundsException when the index is, well, out of bounds, as in:

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?

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 (and assoc) try to create what keys (or indexes) you require.

The special treatment for vectors is mentioned in the assoc docstring:

When applied to a vector, returns a new vector that contains val at index. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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