This overload is largely harmless but also largely useless.
You’re defining this for your own sampler type, so this is not an instance of type piracy. I.e., nothing that anybody has written without knowledge or use of your code will break. That’s why it’s harmless.
However, this has “violated” the output interface that every “normal” use of Base.rand
has assumed, so you should not expect to be able to pass this sampler to other code that has a “normal” use and have it work properly (if at all). For example, you can’t pass this particular sampler to, e.g., some randomized linear algebra routine that attempts to call Base.rand(rng, sampler, M, N)
(forgive me if the syntax there is slightly wrong – I haven’t experimented with custom samplers) to produce a random Matrix
that it then uses for some calculation.
The main reason to add methods to existing functions is to orthogonalize algorithms from data types. I.e., the same calculation can be used to compute the exp
of a Float32
or a square Matrix{T}
for a wide range of suitable T
(although in practice there are different optimizations and tradeoffs made, which is why we define specializations for both): all that is required is that +
and *
have suitable and “equivalent” definitions for either type.
But since the array output of your proposed sampler is nonstandard, it’s not an “equivalent” use. Other code has made assumptions about the output of Base.rand
(i.e., that it can be used to produce an Array
of values but not a Dict
of Array
s) will be violated and the following code will be unlikely to work.
That is why I say that there isn’t a benefit to specializing Base.rand
for this – existing uses of Base.rand
should not be expected to function for this. This is why I say that such an overload is largely “useless” and I suggest a different function altogether. With a different function, you’ll be less likely to confuse yourself (or other people) thinking that this would work with standard Base.rand
uses.
Since you say you’re only planning to call this within your module, there isn’t a operational reason to use Base.rand
over some new function. If it’s still useful to define the sampler this way because the other machinery in the RNG interface saves you needing to re-write a bunch of extra boilerplate, go ahead and save yourself the trouble. But if you’re needing to re-implement most everything anyway, then Base.rand
isn’t doing you any favors and is risking semantic confusion.