From 31dbd258985545c9377b9bb2334aa87fa8cabee2 Mon Sep 17 00:00:00 2001 From: Rafael Fourquet Date: Thu, 16 Aug 2018 20:54:22 +0200 Subject: [PATCH] add rand(::Type{<:Pair} --- stdlib/Random/src/Random.jl | 2 +- stdlib/Random/src/generation.jl | 12 ++++++++++++ stdlib/Random/test/runtests.jl | 6 ++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/stdlib/Random/src/Random.jl b/stdlib/Random/src/Random.jl index 42aebc1344d42..456f788515795 100644 --- a/stdlib/Random/src/Random.jl +++ b/stdlib/Random/src/Random.jl @@ -290,7 +290,7 @@ Pick a random element or array of random elements from the set of values specifi * a string (considered as a collection of characters), or * a type: the set of values to pick from is then equivalent to `typemin(S):typemax(S)` for integers (this is not applicable to [`BigInt`](@ref)), and to ``[0, 1)`` for floating - point numbers; + point numbers; `S` can also be a `Pair` type, in which case random pairs are produced; `S` defaults to [`Float64`](@ref) (except when `dims` is a tuple of integers, in which case `S` must be specified). diff --git a/stdlib/Random/src/generation.jl b/stdlib/Random/src/generation.jl index 7ec0c3930eb32..b9024707189b7 100644 --- a/stdlib/Random/src/generation.jl +++ b/stdlib/Random/src/generation.jl @@ -161,6 +161,18 @@ function rand(r::AbstractRNG, ::SamplerType{T}) where {T<:AbstractChar} (c < 0xd800) ? T(c) : T(c+0x800) end +### random pairs + +function Sampler(RNG::Type{<:AbstractRNG}, ::Type{Pair{A,B}}, n::Repetition) where {A,B} + sp1 = Sampler(RNG, A, n) + sp2 = A === B ? sp1 : Sampler(RNG, B, n) + SamplerTag{Tuple{Pair{A,B}}}(sp1 => sp2) # Tuple so that the gentype is Pair{A,B} + # in SamplerTag's constructor +end + +rand(rng::AbstractRNG, sp::SamplerTag{<:Tuple{<:Pair}}) = + rand(rng, sp.data.first) => rand(rng, sp.data.second) + ## Generate random integer within a range diff --git a/stdlib/Random/test/runtests.jl b/stdlib/Random/test/runtests.jl index 91d3db9eb994a..dd3dfa18022bf 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(::Type{<:Pair})" begin + @test rand(Pair{Int,Int}) isa Pair{Int,Int} + @test rand(Pair{Int,Float64}) isa Pair{Int,Float64} + @test rand(Pair{Int,Float64}, 3) isa Array{Pair{Int,Float64}} +end