Is it always true that
length(x) == length(eachindex(x))
?
I think so, but I usually do prod(size(x))
for arrays just because I never remember what length
is supposed to be on them.
length
and eachindex
are generic, so no?
According to the docstrings:
length
: Return the number of elements in the collection.eachindex
: Create an iterable object for visiting each index of an AbstractArray
.I would interpret this as yes, assuming the methods follow the documentation.
Well that is only part of the description of eachindex
. It can be defined for anything iterable, including unbounded sequences.
Just today I implemented it for a non-AbstractArray
type as recommended by @Sukera. There's nothing wrong with that.
do note that I just recommended it due to being a convenient name, not for implying your Rect
was an AbstractArray
Exactly.
(though the docstring does support "other iterables" as well)
Right, that is my point, that it is not exclusive to arrays.
So, if the sequence is bounded, then "yes"? Or do you see any other pathological case?
I think they should be the same in all cases.
Michael Fiano said:
Right, that is my point, that it is not exclusive to arrays.
What does that have to do with it though? The question isn't about arrays in particular, it's about whether length
of an object should agree with the length of it's indices, and I'd say that in every case where indices exist, they should absolutely be the same.
Of course one can always just define a method that does something whacky, but I think defining an object where it's length doesn't agree with the length of it's indices is far enough beyond the pale that it can be ignored.
Gunnar Farnebäck said:
According to the docstrings:
length
: Return the number of elements in the collection.eachindex
: Create an iterable object for visiting each index of anAbstractArray
.I would interpret this as yes, assuming the methods follow the documentation.
That wasn't in response to the original question, moreso than it was in response to the partial documentation quoting here.
I agree with that assumption. I did however implement eachindex
on a non-array (without an accompanying length
implementation) to make iteration on a type more concise, so in that particular case, which satisfied my needs, they are technically different, seeing how one is a MethodError
.
Leandro Martínez has marked this topic as resolved.
Thank you all!
Last updated: Nov 22 2024 at 04:41 UTC