I want to define defaults for a read-only AbstractVector{Bool} argument to a function and so far used falses(n). However, this allocates a full BitArray.
I guess should be a type similar to a Range that can do this job, similar to:
struct Repeat{T,N} end
Base.getindex(r::Repeat{T,N},i::Int) where {T,N} =
(1 <= i <= N) ? T : throw(BoundsError(r,i))
Base.length(r::Repeat{T,N}) where {T,N} = N
Before I invest much time in developing such a type with the full Array interface, I ask how such cases are handled so far in Julia?
Something close to what you want already exists (in Base):
help?> Iterators.repeated
repeated(x[, n::Int])
An iterator that generates the value x forever. If n is specified, generates x
that many times (equivalent to take(repeated(x), n)).
Examples
≡≡≡≡≡≡≡≡≡≡
julia> a = Iterators.repeated([1 2], 4);
julia> collect(a)
4-element Array{Array{Int64,2},1}:
[1 2]
[1 2]
[1 2]
[1 2]
I checked and it supports length. However, it does not support indexing (i.e., a[1] will fail). Did you search for packages, I find strange nobody implemented that. As @jipolanco pointed out this already exists.
Also, I would not recommend putting the length in a type parameter of the struct, otherwise your code will be re-compiled each time you pass a Repeat of different size to your functions. StaticArrays does this for very small and “often the same size” objects.