NTuple{N}(v) silently truncates when length(v) > N

MWE:

julia> NTuple{3}(zeros(4))
(0.0, 0.0, 0.0)

I expected an error, am I missing something?

(on Julia 1.10, master, 1.9, etc, this is not new)

The implementation of _totuple in tuple.jl accepts iterables with excess elements but errors on insufficient elements.

What I am unsure about if this is intended, or a bug.

Seems intentional because of the use of Iterators.take in one of the methods.

I don’t think it is, but it can’t hurt to ask, so

I doubt it’ll change anything because you’re supposed to be able to make tuples from iterables that don’t even have a length.

julia> NTuple{7}(Iterators.cycle(1:3))
(1, 2, 3, 1, 2, 3, 1)

julia> length(Iterators.cycle(1:3))
ERROR: MethodError: no method matching length(::Base.Iterators.Cycle{UnitRange{Int64}})

We shall see. I think that silently applying Iterators.take on inputs is a questionable decision. I can live with it, but it should at least be documented.

It is documented that “A tuple can be constructed from an iterator by using a Tuple type as constructor”, and the iteration interface is pretty clear that an iterable does not always have a fixed length. If a tuple can be constructed from an iterable with unfixed length, it’s not reasonable to error on iterables with a greater fixed length; both kinds of iterables are “silently truncated” the same way. _totuple does work on longer tuples, so an input tuple dispatches Tuple constructors to a separate method that may only convert. Maybe this exception should be documented.

1 Like

herea discussion that seems relevant to me

1 Like