Efficient Repeat: Array of single value

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?

You can use FillArrays.jl for this:

julia> using FillArrays

julia> x = Fill(false, 10)
10-element Fill{Bool}: entries equal to false

julia> x[3]
false

julia> x[11]
ERROR: BoundsError: attempt to access 10-element Fill{Bool} at index [11]
Stacktrace:
 [1] throw_boundserror(A::Fill{Bool, 1, Tuple{Base.OneTo{Int64}}}, I::Tuple{Int64})
   @ Base ./abstractarray.jl:645
 [2] checkbounds
   @ ./abstractarray.jl:610 [inlined]
 [3] getindex(F::Fill{Bool, 1, Tuple{Base.OneTo{Int64}}}, kj::Int64)
   @ FillArrays ~/.julia/packages/FillArrays/FPGoE/src/FillArrays.jl:41
 [4] top-level scope
   @ REPL[11]:1
4 Likes

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.

2 Likes

typeof(Falses(4)) <: AbstractArray{Bool}
perfect, Thank you.