Rand and rand! seem inconsistent

Clearly i’m missing something…

julia> rand(UInt8(0):UInt8(15))

julia> rand!(UInt8(0):UInt8(15), zeros(UInt8,5))
ERROR: indexing not defined for UnitRange{UInt8}
 [1] setindex! at ./abstractarray.jl:967 [inlined]
 [2] rand!(::MersenneTwister, ::UnitRange{UInt8}, ::Array{UInt8,1}) at ./random.jl:692
 [3] rand!(::UnitRange{UInt8}, ::Array{UInt8,1}) at ./random.jl:313

Naturally my goal here is to fill an existing array with random values.

You have the argument order reversed, try:

julia> rand!(zeros(UInt8,5), UInt8(0):UInt8(15))
5-element Array{UInt8,1}:
1 Like

oh, i see. i’m having trouble with reading comprehension :

Populate the array A with random values. If the indexable collection coll is specified, the values are picked randomly from coll. This is equivalent to copy!(A, rand(rng, coll, size(A)))

I think it would be more clear if rand! defined [coll] to be [S] like rand does, or is there some subtle difference in how the two routine select random values ?

Thanks !

edit: furthermore i think it’s pretty consistent in julia that the first arg is the argument which is mutated in ! functions - is that fair to say ?

Yeah, the first argument is almost always the one being mutated.

I think S is allowed to be either a type or a collection, whereas coll is only allowed to be a collection. If you think that could be reworded more clearly, I’m sure a PR would be very welcome!

The argument order convention used by base Julia is documented here: https://docs.julialang.org/en/latest/manual/style-guide/#Write-functions-with-argument-ordering-similar-to-Julia’s-Base-1