Skip to content

Commit

Permalink
add rand(::Type{<:Pair}
Browse files Browse the repository at this point in the history
  • Loading branch information
rfourquet committed Aug 16, 2018
1 parent d936625 commit 31dbd25
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
2 changes: 1 addition & 1 deletion stdlib/Random/src/Random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
12 changes: 12 additions & 0 deletions stdlib/Random/src/generation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
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(::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

0 comments on commit 31dbd25

Please sign in to comment.