From b98079798ecf8ef0c75594a6aacada84df8913c0 Mon Sep 17 00:00:00 2001 From: Rafael Fourquet Date: Thu, 16 Aug 2018 20:00:15 +0200 Subject: [PATCH] add rand(::Pair) --- stdlib/Random/src/generation.jl | 9 +++++++++ stdlib/Random/test/runtests.jl | 6 ++++++ 2 files changed, 15 insertions(+) diff --git a/stdlib/Random/src/generation.jl b/stdlib/Random/src/generation.jl index 7ec0c3930eb32..14348a0cf4500 100644 --- a/stdlib/Random/src/generation.jl +++ b/stdlib/Random/src/generation.jl @@ -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)] diff --git a/stdlib/Random/test/runtests.jl b/stdlib/Random/test/runtests.jl index 91d3db9eb994a..3295264954778 100644 --- a/stdlib/Random/test/runtests.jl +++ b/stdlib/Random/test/runtests.jl @@ -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