Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add rand(::Pair) #28704

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions stdlib/Random/src/generation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -430,3 +430,12 @@ function rand(rng::AbstractRNG, sp::SamplerSimple{<:AbstractString,<:Sampler})::
isvalid_unsafe(str, pos) && return str[pos]
end
end


## random elements from pairs

Sampler(RNG::Type{<:AbstractRNG}, t::Pair, n::Repetition) =
SamplerSimple(t, Sampler(RNG, Bool, n))

rand(rng::AbstractRNG, sp::SamplerSimple{<:Pair}) =
@inbounds return sp[][1 + rand(rng, sp.data)]
6 changes: 6 additions & 0 deletions stdlib/Random/test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -686,3 +686,9 @@ end
@test Random.gentype(Random.UInt52(UInt128)) == UInt128
@test Random.gentype(Random.UInt104()) == UInt128
end

@testset "rand(::Pair)" begin
@test rand(1=>3) ∈ (1, 3)
@test rand(1=>2, 3) isa Vector{Int}
@test rand(1=>'2', 3) isa Vector{Union{Char, Int}}
end