Skip to content

Commit

Permalink
add Rand objects
Browse files Browse the repository at this point in the history
  • Loading branch information
rfourquet committed Dec 5, 2017
1 parent 20030fd commit 0bd67f0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
8 changes: 4 additions & 4 deletions base/random/generation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ rand_ui52(r::AbstractRNG) = rand_ui52_raw(r) & 0x000fffffffffffff

### sampler for pairs and complex numbers

function Sampler(rng::AbstractRNG, u::Distribution2{T}, n::Repetition) where T <: Union{Complex,Pair}
function Sampler(rng::AbstractRNG, u::Combine2{T}, n::Repetition) where T <: Union{Complex,Pair}
sp1 = Sampler(rng, u.x, n)
sp2 = u.x == u.y ? sp1 : Sampler(rng, u.y, n)
SamplerTag{Cont{T}}((sp1, sp2))
Expand All @@ -126,11 +126,11 @@ rand(rng::AbstractRNG, sp::SamplerTag{Cont{T}}) where {T<:Union{Complex,Pair}} =

#### additional methods for complex numbers

Sampler(rng::AbstractRNG, u::Distribution1{Complex}, n::Repetition) =
Sampler(rng, Distribution(Complex, u.x, u.x), n)
Sampler(rng::AbstractRNG, u::Combine1{Complex}, n::Repetition) =
Sampler(rng, Combine(Complex, u.x, u.x), n)

Sampler(rng::AbstractRNG, ::Type{Complex{T}}, n::Repetition) where {T<:Real} =
Sampler(rng, Distribution(Complex, T, T), n)
Sampler(rng, Combine(Complex, T, T), n)

### random characters

Expand Down
27 changes: 27 additions & 0 deletions base/random/random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,33 @@ rand(::Type{BitArray}, dims::Dims) = rand!(BitArray(uninitialized, dims))
rand(::Type{BitArray}, dims::Integer...) = rand!(BitArray(uninitialized, convert(Dims, dims)))


### Rand

struct Rand{R<:AbstractRNG,S<:Sampler}
rng::R
sp::S
end

# X can be an explicit Distribution, or an implicit one like 1:10
Rand(rng::AbstractRNG, X) = Rand(rng, Sampler(rng, X))
Rand(rng::AbstractRNG, ::Type{X}) where {X} = Rand(rng, Sampler(rng, X))

Rand(X) = Rand(GLOBAL_RNG, X)
Rand(::Type{X}) where {X} = Rand(GLOBAL_RNG, X)

(R::Rand)(args...) = rand(R.rng, R.sp, args...)

Base.start(R::Rand) = R

function Base.next(R::Rand, ::Rand)
e = R()
e, R
end

Base.done(R::Rand, ::Rand) = false

Base.iteratorsize(::Type{<:Rand}) = Base.IsInfinite()

## __init__ & include

function __init__()
Expand Down

0 comments on commit 0bd67f0

Please sign in to comment.