Random: introduce gentype, instead of punning on eltype #27756
Random: introduce gentype, instead of punning on eltype #27756
Conversation
Could you provide an example with such a case? |
|
I initially used Two main use-cases for random generation:
As by default Actually, going away from
So Finally, there is an example where one would like to define both struct Die
sides::Vector{Int}
end
rand(::Type{Die}) = Die(rand(1:12, 6))
rand(d::Die) = rand(d.sides)
gentype(::Die) = IntI.e. we don't necessarily want |
|
I will merge by tomorrow if no objection. |
|
Can you give an example where it would be useful to have |
|
I guess we would also have |
Indeed, in this example. That said, here the Again, we could keep |
Couldn't we just hardcode that types generate elements of themselves and only use eltype for non-types. I realize that matches the |
I agree with this point, and I'm not clear to which extent it turns out to be problematic in practice. One workaround, which is somewhat ugly, would be to use instead: # users define those, which have defaults:
gentype(::Type{T}) where T = eltype(T) # for objects, useful default for e.g. rand(1:9)
gentype(::Type{Type{T}}) where T = T # for types, useful default for e.g. rand(Die)
# in the Random library, get the gentype for an object when only an instance is available, not its type:
gentypefromvalue(::X) where X = gentype(X)
gentypefromvalue(::Type{X}) where X = gentype(Type{X}) |
In that respect, I indeed don't imagine yet a case where one would want
I don't really like the first and 3rd bullets, but I guess it's not a big deal. On the other hand, with |
|
Very high-level comment, I get very suspicious of an API when it needs to do this kind of fiddly disambiguation between operating in the value domain and the type domain. |
I don't disagree, and it's a bit tricky to find the right design here for this reason, but the fact is that for Given the feedback, I see two solutions forward:
I prefer option 2), as again I don't like punning on |
|
Maybe a small vote: 👍 here for |
|
I updated according to option 2 above, and will merge by tomorrow if no decision is taken otherwise (for option 1). In the documentation I wrote, there is no mention of |
In some cases it makes sense to define what type of value `rand(rng, x)` will produce, via the newly introduced `gentype(x)`, without having `eltype(x)` be meaningful.
c78c880 to
b072867
Compare
In some cases it makes sense to define what type of value
rand(rng, x)will produce, via the newly introduced
gentype(x), without havingeltype(x)be meaningful.