Skip to content

Commit 61ace50

Browse files
committed
enable rand([X], ::Type{<:NamedTuple})
1 parent 644f980 commit 61ace50

3 files changed

Lines changed: 16 additions & 1 deletion

File tree

README.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,9 +180,12 @@ julia> julia> rand(Bernoulli(0.2), BitVector, 10) # using the Bernoulli distribu
180180
julia> rand(1:3, NTuple{3}) # NTuple{3} considered as a container, equivalent to rand(make(NTuple{3}, 1:3))
181181
(3, 3, 1)
182182

183-
julia> rand(1:3, Tuple{Int,UInt8, BigFloat}) # works also with more general tuple types
183+
julia> rand(1:3, Tuple{Int,UInt8, BigFloat}) # works also with more general tuple types ...
184184
(3, 0x02, 2.0)
185185

186+
julia> rand(1:3, NamedTuple{(:a, :b)}) # ... and with named tuples
187+
(a = 3, b = 2)
188+
186189
julia> RandomExtensions.random_staticarrays() # poor man's conditional modules!
187190
# ugly warning
188191

src/containers.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,12 @@ end
7575
@make_container(T::Type{<:Tuple})
7676
@make_container(::Type{Tuple}, n::Integer)
7777
@make_container(T::Type{NTuple{N,TT} where N} => TT, n::Integer)
78+
@make_container(T::Type{<:NamedTuple{K}} => K)
79+
80+
if VERSION < v"1.1.0"
81+
# disambiguate
82+
rand(rng::AbstractRNG, ::Type{NamedTuple}) = rand(rng, make(NamedTuple))
83+
end
7884

7985
## arrays (same as in Random, but with explicit type specification, e.g. rand(Int, Array, 4)
8086

test/runtests.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,12 @@ end
416416
t = rand(make(NamedTuple{(:a, :b),Tuple{Float64,UInt8}}, 1:3))
417417
@test t isa NamedTuple{(:a, :b), Tuple{Float64,UInt8}}
418418
@test t.a 1:3 && t.b 1:3
419+
420+
# as container
421+
@test rand(1:3, NamedTuple{(:a,)}) isa NamedTuple{(:a,), Tuple{Int}}
422+
@test rand(1:3, NamedTuple{(:a,), Tuple{Float64}}) isa NamedTuple{(:a,), Tuple{Float64}}
423+
@test rand(1:3, NamedTuple{(:a, :b)}) isa NamedTuple{(:a, :b), Tuple{Int,Int}}
424+
@test rand(1:3, NamedTuple{(:a, :b), Tuple{Float64,Float64}}) isa NamedTuple{(:a, :b), Tuple{Float64,Float64}}
419425
end
420426

421427
@testset "rand(make(String, ...))" begin

0 commit comments

Comments
 (0)