licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
10420
# This file contains the basic functions of PCG. import RandomNumbers: AbstractRNG "Return the default multiplier for a certain type." @inline default_multiplier(::Type{UInt8}) = 0x8d @inline default_multiplier(::Type{UInt16}) = 0x321d @inline default_multiplier(::Type{UInt32}) = 0x2c9277b5 @inline default_multiplier(::Type{UInt64}) = 0x5851f42d4c957f2d @inline default_multiplier(::Type{UInt128}) = 0x2360ed051fc65da44385df649fccf645 "Return the default increment for a certain type." @inline default_increment(::Type{UInt8}) = 0x4d @inline default_increment(::Type{UInt16}) = 0xbb75 @inline default_increment(::Type{UInt32}) = 0xac564b05 @inline default_increment(::Type{UInt64}) = 0x14057b7ef767814f @inline default_increment(::Type{UInt128}) = 0x5851f42d4c957f2d14057b7ef767814f "Return the default MCG multiplier for a certain type." @inline mcg_multiplier(::Type{UInt8}) = 0xd9 @inline mcg_multiplier(::Type{UInt16}) = 0xf2d9 @inline mcg_multiplier(::Type{UInt32}) = 0x108ef2d9 @inline mcg_multiplier(::Type{UInt64}) = 0xaef17502108ef2d9 @inline mcg_multiplier(::Type{UInt128}) = 0xf69019274d7f699caef17502108ef2d9 "Return the default MCG unmultiplier for a certain type." @inline mcg_unmultiplier(::Type{UInt8}) = 0x69 @inline mcg_unmultiplier(::Type{UInt16}) = 0x6d69 @inline mcg_unmultiplier(::Type{UInt32}) = 0xacb86d69 @inline mcg_unmultiplier(::Type{UInt64}) = 0xd04ca582acb86d69 @inline mcg_unmultiplier(::Type{UInt128}) = 0xc827645e182bc965d04ca582acb86d69 @inline uint_index(::Type{UInt8}) = 1 @inline uint_index(::Type{UInt16}) = 2 @inline uint_index(::Type{UInt32}) = 3 @inline uint_index(::Type{UInt64}) = 4 @inline uint_index(::Type{UInt128}) = 5 @inline half_width(::Type{UInt16}) = UInt8 @inline half_width(::Type{UInt32}) = UInt16 @inline half_width(::Type{UInt64}) = UInt32 @inline half_width(::Type{UInt128}) = UInt64 # Shift and Rotate functions # Rotate functions. @inline function pcg_rotr(value::T, rot::T) where T <: PCGUInt s = sizeof(T) << 3 (value >> (rot % s)) | (value << (-rot % s)) end "General advance functions." @inline function pcg_advance_lcg(state::T, delta::T, cur_mult::T, cur_plus::T) where T <: PCGUInt acc_mult = 1 % T acc_plus = 0 % T while delta > 0 if delta & 1 == 1 acc_mult *= cur_mult acc_plus = acc_plus * cur_mult + cur_plus end cur_plus = (cur_mult + (1 % T)) * cur_plus cur_mult *= cur_mult delta = delta >> 1 end acc_mult * state + acc_plus end # output_xsh_rs # Xorshift High, Random Shift. # return half bits of T. @inline function pcg_output(state::T, ::Type{PCG_XSH_RS}) where T <: Union{pcg_uints[2:end]...} return_bits = sizeof(T) << 2 bits = return_bits << 1 spare_bits = bits - return_bits op_bits = spare_bits - 5 >= 64 ? 5 : spare_bits - 4 >= 32 ? 4 : spare_bits - 3 >= 16 ? 3 : spare_bits - 2 >= 4 ? 2 : spare_bits - 1 >= 1 ? 1 : 0 mask = (1 << op_bits) - 1 xshift = op_bits + (return_bits + mask) >> 1 rshift = op_bits != 0 ? (state >> (bits - op_bits)) & mask : 0 % T state = state ⊻ (state >> xshift) (state >> (spare_bits - op_bits - mask + rshift)) % half_width(T) end # output_xsh_rr # Xorshift High, Random Rotation. # return half bits of T. @inline function pcg_output(state::T, ::Type{PCG_XSH_RR}) where T <: Union{pcg_uints[2:end]...} return_bits = sizeof(T) << 2 bits = return_bits << 1 spare_bits = bits - return_bits op_bits = return_bits >= 128 ? 7 : return_bits >= 64 ? 6 : return_bits >= 32 ? 5 : return_bits >= 16 ? 4 : 3 mask = (1 << op_bits) - 1 xshift = (op_bits + return_bits) >> 1 rot = (state >> (bits - op_bits)) & mask state ⊻= (state >> xshift) result = (state >> (spare_bits - op_bits)) % half_width(T) pcg_rotr(result, rot % half_width(T)) end # output_rxs_m_xs # Random Xorshift, Multiplication, Xorshift. # return the same bits as T. # Insecure. @inline function pcg_output(state::T, ::Type{PCG_RXS_M_XS}) where T <: PCGUInt bits = return_bits = sizeof(T) << 3 op_bits = return_bits >= 128 ? 6 : return_bits >= 64 ? 5 : return_bits >= 32 ? 4 : return_bits >= 16 ? 3 : 2 mask = (1 << op_bits) - 1 rshift = (state >> (bits - op_bits)) & mask state ⊻= state >> (op_bits + rshift) state *= mcg_multiplier(T) state ⊻ (state >> ((return_bits << 1 + 2) ÷ 3)) end # output_xsl_rr # Xorshift Low, Random Rotation. # return half bits of T. @inline function pcg_output(state::T, ::Type{PCG_XSL_RR}) where T <: Union{UInt64, UInt128} return_bits = sizeof(T) << 2 bits = return_bits << 1 spare_bits = bits - return_bits op_bits = return_bits >= 128 ? 7 : return_bits >= 64 ? 6 : return_bits >= 32 ? 5 : return_bits >= 16 ? 4 : 3 mask = (1 << op_bits) - 1 xshift = (spare_bits + return_bits) >> 1 rot = (state >> (bits - op_bits)) & mask pcg_rotr((state ⊻ (state >> xshift)) % half_width(T), rot % half_width(T)) end # output_xsl_rr_rr # Xorshift Low, Random Rotation, Random Rotation. # return the same bits as T. # Insecure. @inline function pcg_output(state::T, ::Type{PCG_XSL_RR_RR}) where T <: Union{UInt64, UInt128} half_bits = sizeof(T) << 2 bits = half_bits << 1 spare_bits = bits - half_bits op_bits = half_bits >= 128 ? 7 : half_bits >= 64 ? 6 : half_bits >= 32 ? 5 : half_bits >= 16 ? 4 : 3 mask = (1 << op_bits) - 1 xshift = (spare_bits + half_bits) >> 1 rot = (state >> (bits - op_bits)) & mask state ⊻= state >> xshift low_bits = state % half_width(T) low_bits = pcg_rotr(low_bits, rot % half_width(T)) high_bits = (state >> spare_bits) % half_width(T) rot2 = low_bits & mask high_bits = pcg_rotr(high_bits, rot2 % half_width(T)) ((high_bits % T) << spare_bits) ⊻ (low_bits % T) end # PCGState types, SRandom and Step functions. """ ```julia AbstractPCG{StateType<:PCGUInt, MethodType<:PCGMethod, OutputType<:PCGUInt} <: AbstractRNG{OutputType} ``` The base abstract type for PCGs. """ abstract type AbstractPCG{StateType<:PCGUInt, MethodType<:PCGMethod, OutputType<:PCGUInt } <: AbstractRNG{OutputType} end # pcg_state_XX # XX is one of the UInt types. mutable struct PCGStateOneseq{StateType<:PCGUInt, MethodType<:PCGMethod, OutputType<:PCGUInt} <: AbstractPCG{StateType, MethodType, OutputType} state::StateType PCGStateOneseq{StateType, MethodType, OutputType}() where {StateType<:PCGUInt, MethodType<:PCGMethod, OutputType<:PCGUInt} = new() end @inline function pcg_seed!(s::PCGStateOneseq{T}, init_state::T) where T <: PCGUInt s.state = 0 % T pcg_step!(s) s.state += init_state pcg_step!(s) s end # pcg_oneseq_XX_step_r # XX is one of the UInt types. @inline function pcg_step!(s::PCGStateOneseq{T}) where T <: PCGUInt s.state = s.state * default_multiplier(T) + default_increment(T) end # pcg_oneseq_XX_advance_r # XX is one of the UInt types. @inline function pcg_advance!(s::PCGStateOneseq{T}, delta::T) where T <: PCGUInt s.state = pcg_advance_lcg(s.state, delta, default_multiplier(T), default_increment(T)) end # pcg_state_XX # XX is one of the UInt types. mutable struct PCGStateMCG{StateType<:PCGUInt, MethodType<:PCGMethod, OutputType<:PCGUInt} <: AbstractPCG{StateType, MethodType, OutputType} state::StateType PCGStateMCG{StateType, MethodType, OutputType}() where {StateType<:PCGUInt, MethodType<:PCGMethod, OutputType<:PCGUInt} = new() end @inline function pcg_seed!(s::PCGStateMCG{T}, init_state::T) where T <: PCGUInt s.state = init_state | 1 s end # pcg_mcg_XX_step_r # XX is one of the UInt types. @inline function pcg_step!(s::PCGStateMCG{T}) where T <: PCGUInt s.state = s.state * default_multiplier(T) end # pcg_mcg_XX_advance_r # XX is one of the UInt types. @inline function pcg_advance!(s::PCGStateMCG{T}, delta::T) where T <: PCGUInt s.state = pcg_advance_lcg(s.state, delta, default_multiplier(T), 0 % T) end # pcg_state_XX # XX is one of the UInt types. mutable struct PCGStateUnique{StateType<:PCGUInt, MethodType<:PCGMethod, OutputType<:PCGUInt} <: AbstractPCG{StateType, MethodType, OutputType} state::StateType PCGStateUnique{StateType, MethodType, OutputType}() where {StateType<:PCGUInt, MethodType<:PCGMethod, OutputType<:PCGUInt} = new() end @inline function pcg_seed!(s::PCGStateUnique{T}, init_state::T) where T <: PCGUInt s.state = 0 % T pcg_step!(s) s.state += init_state pcg_step!(s) s end # pcg_unique_XX_step_r # XX is one of the UInt types. @inline function pcg_step!(s::PCGStateUnique{T}) where T <: PCGUInt s.state = s.state * default_multiplier(T) + (UInt(pointer_from_objref(s)) | 1) % T end # pcg_unique_XX_advance_r # XX is one of the UInt types. @inline function pcg_advance!(s::PCGStateUnique{T}, delta::T) where T <: PCGUInt s.state = pcg_advance_lcg(s.state, delta, default_multiplier(T), (UInt(pointer_from_objref(s)) | 1) % T) end # pcg_state_XX # XX is one of the UInt types. mutable struct PCGStateSetseq{StateType<:PCGUInt, MethodType<:PCGMethod, OutputType<:PCGUInt} <: AbstractPCG{StateType, MethodType, OutputType} state::StateType inc::StateType PCGStateSetseq{StateType, MethodType, OutputType}() where {StateType<:PCGUInt, MethodType<:PCGMethod, OutputType<:PCGUInt} = new() end @inline function pcg_seed!(s::PCGStateSetseq{T}, init_state::T, init_seq::T) where T <: PCGUInt s.state = 0 s.inc = (init_seq << 1) | 1 pcg_step!(s) s.state += init_state pcg_step!(s) s end # pcg_setseq_XX_step_r # XX is one of the UInt types. @inline function pcg_step!(s::PCGStateSetseq{T}) where T <: PCGUInt s.state = s.state * default_multiplier(T) + s.inc end # pcg_setseq_XX_advance_r # XX is one of the UInt types. @inline function pcg_advance!(s::PCGStateSetseq{T}, delta::T) where T <: PCGUInt s.state = pcg_advance_lcg(s.state, delta, default_multiplier(T), s.inc) end "Return the output of a state for a certain PCG type." pcg_output "Initialize a PCG object." pcg_seed! "Do one iteration step for a PCG object." pcg_step! "Advance a PCG object." pcg_advance!
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
7869
import Base: copy, copyto!, == import Random: rand, seed! import RandomNumbers: gen_seed, seed_type # Generic functions @inline seed!(r::AbstractPCG{StateType}, seed::Integer=gen_seed(StateType)) where StateType <: PCGUInt = pcg_seed!(r, seed % StateType) @inline seed!(r::PCGStateSetseq{StateType}, seed::NTuple{2, Integer}=gen_seed(StateType, 2)) where StateType <: PCGUInt = pcg_seed!(r, seed[1] % StateType, seed[2] % StateType) @inline seed_type(::Type{PCGStateOneseq{T, T1, T2}}) where {T, T1, T2} = T @inline seed_type(::Type{PCGStateMCG{ T, T1, T2}}) where {T, T1, T2} = T @inline seed_type(::Type{PCGStateUnique{T, T1, T2}}) where {T, T1, T2} = T @inline seed_type(::Type{PCGStateSetseq{T, T1, T2}}) where {T, T1, T2} = NTuple{2, T} function copyto!(dest::T, src::T) where T <: AbstractPCG dest.state = src.state dest end function copyto!(dest::T, src::T) where T <: PCGStateSetseq dest.state = src.state dest.inc = src.inc dest end copy(src::T) where T <: AbstractPCG = copyto!(T(), src) ==(r1::T, r2::T) where T <: AbstractPCG = r1.state == r2.state ==(r1::T, r2::T) where T <: PCGStateSetseq = r1.state == r2.state && r1.inc == r2.inc @inline function rand(r::AbstractPCG{StateType, MethodType, OutputType}, ::Type{OutputType}) where {StateType <: Union{pcg_uints[1:end-1]...}, MethodType <: PCGMethod, OutputType <: PCGUInt} old_state = r.state pcg_step!(r) pcg_output(old_state, MethodType) end @inline function rand(r::AbstractPCG{UInt128, MethodType, OutputType}, ::Type{OutputType}) where {MethodType <: PCGMethod, OutputType <: PCGUInt} pcg_step!(r) pcg_output(r.state, MethodType) end """ ```julia bounded_rand(r, bound) ``` Producing a random number less than a given `bound` in the output type. """ @inline function bounded_rand(s::AbstractPCG{StateType, MethodType, OutputType}, bound::OutputType) where {StateType <: PCGUInt, MethodType <: PCGMethod, OutputType <: PCGUInt} threshold = (-bound) % bound r = rand(s, OutputType) while r < threshold r = rand(s, OutputType) end r % bound end """ ```julia advance!(r, Ξ”) ``` Advance a PCG object `r` for `Ξ”` steps. # Examples ```jldoctest julia> r = PCGStateSetseq(UInt64, PCG_RXS_M_XS, (123, 321)) PCGStateSetseq{UInt64,Val{:RXS_M_XS},UInt64}(0x45389f8b27528b29, 0x0000000000000283) julia> A = rand(r, UInt64, 2); julia> p = rand(r); julia> r PCGStateSetseq{UInt64,Val{:RXS_M_XS},UInt64}(0x9b1fc763ae0ad702, 0x0000000000000283) julia> advance!(r, -3) PCGStateSetseq{UInt64,Val{:RXS_M_XS},UInt64}(0x45389f8b27528b29, 0x0000000000000283) julia> @Test.test A == rand(r, UInt64, 2) Test Passed julia> @Test.test p == rand(r) Test Passed ``` """ @inline function advance!(r::AbstractPCG{StateType}, Ξ”::Integer) where StateType <: PCGUInt pcg_advance!(r, Ξ” % StateType) r end # Constructors. for (pcg_type_t, uint_type, method_symbol, output_type) in PCG_LIST pcg_type = Symbol("PCGState$pcg_type_t") method = Val{method_symbol} if pcg_type_t != :Setseq @eval function $pcg_type(output_type::Type{$output_type}, method::Type{$method}, seed::Integer=gen_seed($uint_type)) s = $pcg_type{$uint_type, method, output_type}() seed!(s, seed) s end else @eval function $pcg_type(output_type::Type{$output_type}, method::Type{$method}, seed::NTuple{2, Integer}=gen_seed($uint_type, 2)) s = $pcg_type{$uint_type, method, output_type}() seed!(s, seed) s end end end """ ```julia PCGStateOneseq{StateType<:PCGUInt, MethodType<:PCGMethod, OutputType<:PCGUInt} <: AbstractPCG{StateType, MethodType, OutputType} PCGStateOneseq([seed]) PCGStateOneseq(output_type[, seed]) PCGStateOneseq(method[, seed]) PCGStateOneseq(output_type[, method, seed]) ``` PCG generator with *single streams*, where all instances use the same fixed constant, thus the RNG always somewhere in same sequence. `seed` is an `Integer` which will be automatically converted to the state type. `output_type` is the type of the PCG's output. If missing it is set to `UInt64`. `method` is one of the [`PCGMethod`](@ref). If missing it is set to `PCG_XSH_RS`. See [`PCG_LIST`](@ref) for the available parameter combinations. """ PCGStateOneseq(seed::Integer=gen_seed(UInt128)) = PCGStateOneseq(UInt64, PCG_XSH_RS, seed) PCGStateOneseq(::Type{T}, seed::Integer=gen_seed(UInt128)) where T <: PCGUInt = PCGStateOneseq(T, PCG_XSH_RS, seed) PCGStateOneseq(::Type{T}, seed::Integer=gen_seed(UInt128)) where T <: PCGMethod = PCGStateOneseq(UInt64, T, seed) """ ```julia PCGStateMCG{StateType<:PCGUInt, MethodType<:PCGMethod, OutputType<:PCGUInt} <: AbstractPCG{StateType, MethodType, OutputType} PCGStateMCG([seed]) PCGStateMCG(output_type[, seed]) PCGStateMCG(method[, seed]) PCGStateMCG(output_type[, method, seed]) ``` PCG generator with *MCG*, where the increment is zero, resulting in a single stream and reduced period. `seed` is an `Integer` which will be automatically converted to the state type. `output_type` is the type of the PCG's output. If missing it is set to `UInt64`. `method` is one of the [`PCGMethod`](@ref). If missing it is set to `PCG_XSH_RS`. See [`PCG_LIST`](@ref) for the available parameter combinations. """ PCGStateMCG(seed::Integer=gen_seed(UInt128)) = PCGStateMCG(UInt64, PCG_XSH_RS, seed) PCGStateMCG(::Type{T}, seed::Integer=gen_seed(UInt128)) where T <: PCGUInt = PCGStateMCG(T, PCG_XSH_RS, seed) PCGStateMCG(::Type{T}, seed::Integer=gen_seed(UInt128)) where T <: PCGMethod = PCGStateMCG(UInt64, T, seed) """ ```julia PCGStateSetseq{StateType<:PCGUInt, MethodType<:PCGMethod, OutputType<:PCGUInt} <: AbstractPCG{StateType, MethodType, OutputType} PCGStateSetseq([seed]) PCGStateSetseq(output_type[, seed]) PCGStateSetseq(method[, seed]) PCGStateSetseq(output_type[, method, seed]) ``` PCG generator with *specific streams*, where the constant can be changed at any time, selecting a different random sequence. `seed` is a `Tuple` of two `Integer`s which will both be automatically converted to the state type. `output_type` is the type of the PCG's output. If missing it is set to `UInt64`. `method` is one of the [`PCGMethod`](@ref). If missing it is set to `PCG_XSH_RS`. See [`PCG_LIST`](@ref) for the available parameter combinations. """ PCGStateSetseq(seed::NTuple{2, Integer}=gen_seed(UInt128, 2)) = PCGStateSetseq(UInt64, PCG_XSH_RS, seed) PCGStateSetseq(::Type{T}, seed::NTuple{2, Integer}=gen_seed(UInt128, 2)) where T <: PCGUInt = PCGStateSetseq(T, PCG_XSH_RS, seed) PCGStateSetseq(::Type{T}, seed::NTuple{2, Integer}=gen_seed(UInt128, 2)) where T <: PCGMethod = PCGStateSetseq(UInt64, T, seed) """ ```julia PCGStateUnique{StateType<:PCGUInt, MethodType<:PCGMethod, OutputType<:PCGUInt} <: AbstractPCG{StateType, MethodType, OutputType} PCGStateUnique([seed]) PCGStateUnique(output_type[, seed]) PCGStateUnique(method[, seed]) PCGStateUnique(output_type[, method, seed]) ``` PCG generator with *unique streams*, where the constant is based on the memory address of the object, thus every RNG has its own unique sequence. `seed` is an `Integer` which will be automatically converted to the state type. `output_type` is the type of the PCG's output. If missing it is set to `UInt64`. `method` is one of the [`PCGMethod`](@ref). If missing it is set to `PCG_XSH_RS`. See [`PCG_LIST`](@ref) for the available parameter combinations. """ PCGStateUnique(seed::Integer=gen_seed(UInt128)) = PCGStateUnique(UInt64, PCG_XSH_RS, seed) PCGStateUnique(::Type{T}, seed::Integer=gen_seed(UInt128)) where T <: PCGUInt = PCGStateUnique(T, PCG_XSH_RS, seed) PCGStateUnique(::Type{T}, seed::Integer=gen_seed(UInt128)) where T <: PCGMethod = PCGStateUnique(UInt64, T, seed)
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
2870
const PCG_LIST = ( (:Oneseq, UInt16, :XSH_RS, UInt8), (:Oneseq, UInt32, :XSH_RS, UInt16), (:Oneseq, UInt64, :XSH_RS, UInt32), (:Oneseq, UInt128, :XSH_RS, UInt64), (:Unique, UInt16, :XSH_RS, UInt8), (:Unique, UInt32, :XSH_RS, UInt16), (:Unique, UInt64, :XSH_RS, UInt32), (:Unique, UInt128, :XSH_RS, UInt64), (:Setseq, UInt16, :XSH_RS, UInt8), (:Setseq, UInt32, :XSH_RS, UInt16), (:Setseq, UInt64, :XSH_RS, UInt32), (:Setseq, UInt128, :XSH_RS, UInt64), (:MCG, UInt16, :XSH_RS, UInt8), (:MCG, UInt32, :XSH_RS, UInt16), (:MCG, UInt64, :XSH_RS, UInt32), (:MCG, UInt128, :XSH_RS, UInt64), (:Oneseq, UInt16, :XSH_RR, UInt8), (:Oneseq, UInt32, :XSH_RR, UInt16), (:Oneseq, UInt64, :XSH_RR, UInt32), (:Oneseq, UInt128, :XSH_RR, UInt64), (:Unique, UInt16, :XSH_RR, UInt8), (:Unique, UInt32, :XSH_RR, UInt16), (:Unique, UInt64, :XSH_RR, UInt32), (:Unique, UInt128, :XSH_RR, UInt64), (:Setseq, UInt16, :XSH_RR, UInt8), (:Setseq, UInt32, :XSH_RR, UInt16), (:Setseq, UInt64, :XSH_RR, UInt32), (:Setseq, UInt128, :XSH_RR, UInt64), (:MCG, UInt16, :XSH_RR, UInt8), (:MCG, UInt32, :XSH_RR, UInt16), (:MCG, UInt64, :XSH_RR, UInt32), (:MCG, UInt128, :XSH_RR, UInt64), (:Oneseq, UInt8, :RXS_M_XS, UInt8), (:Oneseq, UInt16, :RXS_M_XS, UInt16), (:Oneseq, UInt32, :RXS_M_XS, UInt32), (:Oneseq, UInt64, :RXS_M_XS, UInt64), (:Oneseq, UInt128, :RXS_M_XS, UInt128), (:Unique, UInt16, :RXS_M_XS, UInt16), (:Unique, UInt32, :RXS_M_XS, UInt32), (:Unique, UInt64, :RXS_M_XS, UInt64), (:Unique, UInt128, :RXS_M_XS, UInt128), (:Setseq, UInt8, :RXS_M_XS, UInt8), (:Setseq, UInt16, :RXS_M_XS, UInt16), (:Setseq, UInt32, :RXS_M_XS, UInt32), (:Setseq, UInt64, :RXS_M_XS, UInt64), (:Setseq, UInt128, :RXS_M_XS, UInt128), (:Oneseq, UInt64, :XSL_RR, UInt32), (:Oneseq, UInt128, :XSL_RR, UInt64), (:Unique, UInt64, :XSL_RR, UInt32), (:Unique, UInt128, :XSL_RR, UInt64), (:Setseq, UInt64, :XSL_RR, UInt32), (:Setseq, UInt128, :XSL_RR, UInt64), (:MCG, UInt64, :XSL_RR, UInt32), (:MCG, UInt128, :XSL_RR, UInt64), (:Oneseq, UInt64, :XSL_RR_RR, UInt64), (:Oneseq, UInt128, :XSL_RR_RR, UInt128), (:Unique, UInt64, :XSL_RR_RR, UInt64), (:Unique, UInt128, :XSL_RR_RR, UInt128), (:Setseq, UInt64, :XSL_RR_RR, UInt64), (:Setseq, UInt128, :XSL_RR_RR, UInt128) ) let p() = begin s = "The list of all the parameter combinations that can be used for PCG.\n\n" s *= "|Stream variation|State Type|Method Type|Output Type|\n" s *= "|---|---|---|---|\n" for (pcg_type, uint_type, method, output_type) in PCG_LIST s *= "|`PCGState$pcg_type`|`$uint_type`|`PCG_$method`|`$output_type`|\n" end s end @doc p() PCG_LIST end
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
813
__precompile__(true) """ The module for [Xorshift Family](@ref). Provide 8 RNG types (others are to be deprecated): - [`Xoroshiro64Star`](@ref) - [`Xoroshiro64StarStar`](@ref) - [`Xoroshiro128Plus`](@ref) - [`Xoroshiro128StarStar`](@ref) - [`Xoshiro128Plus`](@ref) - [`Xoshiro128StarStar`](@ref) - [`Xoshiro256Plus`](@ref) - [`Xoshiro256StarStar`](@ref) """ module Xorshifts include("common.jl") include("splitmix64.jl") include("xorshift64.jl") include("xorshift128.jl") include("xorshift1024.jl") export Xoroshiro64Star, Xoroshiro64StarStar include("xoroshiro64.jl") export Xoroshiro128Plus, Xoroshiro128StarStar include("xoroshiro128.jl") export Xoshiro128Plus, Xoshiro128StarStar include("xoshiro128.jl") export Xoshiro256Plus, Xoshiro256StarStar include("xoshiro256.jl") include("docs.jl") end
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
166
@inline xorshift_rotl(x::UInt64, k::Int) = (x >>> (0x3f & -k)) | (x << (0x3f & k)) @inline xorshift_rotl(x::UInt32, k::Int) = (x >>> (0x1f & -k)) | (x << (0x1f & k))
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
3242
"Do one iteration and get the current value of a Xorshift RNG object." xorshift_next let doc_xorshift64(r) = """ ```julia $r <: AbstractXorshift64 $r([seed]) ``` $r RNG. The `seed` can be an `UInt64`, or an `Integer` which will be initialized with `SplitMix64`. """ @doc doc_xorshift64("Xorshift64") Xorshift64 @doc doc_xorshift64("Xorshift64Star") Xorshift64Star end @deprecate Xorshift64 Xoshiro256StarStar @deprecate Xorshift64Star Xoshiro256StarStar let doc_xorshift128(r) = """ ```julia $r <: AbstractXorshift128 $r([seed]) ``` $r RNG. The `seed` can be a `Tuple` of two `UInt64`s, or an `Integer` which will be initialized with `SplitMix64`. """ @doc doc_xorshift128("Xorshift128") Xorshift128 @doc doc_xorshift128("Xorshift128Star") Xorshift128Star @doc doc_xorshift128("Xorshift128Plus") Xorshift128Plus end @deprecate Xorshift128 Xoshiro256StarStar @deprecate Xorshift128Star Xoshiro256StarStar @deprecate Xorshift128Plus Xoshiro256StarStar let doc_xorshift1024(r) = """ ```julia $r <: AbstractXorshift1024 $r([seed...]) ``` $r RNG. The `seed` can be a `Tuple` of 16 `UInt64`s, or an `Integer` which will be initialized with `SplitMix64`. """ @doc doc_xorshift1024("Xorshift1024") Xorshift1024 @doc doc_xorshift1024("Xorshift1024Star") Xorshift1024Star @doc doc_xorshift1024("Xorshift1024Plus") Xorshift1024Plus end @deprecate Xorshift1024 Xoshiro256StarStar @deprecate Xorshift1024Star Xoshiro256StarStar @deprecate Xorshift1024Plus Xoshiro256StarStar # TODO: implement Xoroshiro1024Star / Xoroshiro1024StarStar and Xoroshiro512StarStar / Xoroshiro512Plus let doc_xoroshiro64(r) = """ ```julia $r <: AbstractXoroshiro64 $r([seed]) ``` $r RNG. The `seed` can be a `Tuple` of two `UInt32`s, or an `Integer` which will be initialized with `SplitMix64`. """ @doc doc_xoroshiro64("Xoroshiro64Star") Xoroshiro64Star @doc doc_xoroshiro64("Xoroshiro64StarStar") Xoroshiro64StarStar end let doc_xoroshiro128(r) = """ ```julia $r <: AbstractXoroshiro128 $r([seed]) ``` $r RNG. The `seed` can be a `Tuple` of two `UInt64`s, or an `Integer` which will be initialized with `SplitMix64`. """ @doc doc_xoroshiro128("Xoroshiro128") Xoroshiro128 @doc doc_xoroshiro128("Xoroshiro128Star") Xoroshiro128Star @doc doc_xoroshiro128("Xoroshiro128Plus") Xoroshiro128Plus @doc doc_xoroshiro128("Xoroshiro128StarStar") Xoroshiro128StarStar end @deprecate Xoroshiro128 Xoroshiro128Plus @deprecate Xoroshiro128Star Xoroshiro128StarStar let doc_xoshiro128(r) = """ ```julia $r <: AbstractXoshiro128 $r([seed]) ``` $r RNG. The `seed` can be a `Tuple` of four `UInt32`s, a `Tuple` of two, or an `Integer` which will be initialized with `SplitMix64`. """ @doc doc_xoshiro128("Xoshiro128Plus") Xoshiro128Plus @doc doc_xoshiro128("Xoshiro128StarStar") Xoshiro128StarStar end let doc_xoshiro256(r) = """ ```julia $r <: AbstractXoshiro256 $r([seed]) ``` $r RNG. The `seed` can be a `Tuple` of four `UInt64`s, or an `Integer` which will be automatically convert to an `UInt64` number (and then is initialized with SplitMix64). Zero seeds are not acceptable. """ @doc doc_xoshiro256("Xoshiro256Plus") Xoshiro256Plus @doc doc_xoshiro256("Xoshiro256StarStar") Xoshiro256StarStar end
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
1411
import Base: copy, copyto!, == import Random: rand, seed! import RandomNumbers: AbstractRNG, gen_seed, seed_type """ ```julia SplitMix64 <: AbstractRNG{UInt64} SplitMix64([seed]) ``` Used for initializing a random seed. """ mutable struct SplitMix64 <: AbstractRNG{UInt64} x::UInt64 end function SplitMix64(seed::Integer=gen_seed(UInt64)) r = SplitMix64(zero(UInt64)) seed!(r, seed) r end @inline seed_type(::Type{SplitMix64}) = UInt64 function copyto!(dest::SplitMix64, src::SplitMix64) dest.x = src.x dest end copy(src::SplitMix64) = copyto!(SplitMix64(zero(UInt64)), src) ==(r1::SplitMix64, r2::SplitMix64) = r1.x == r2.x function seed!(r::SplitMix64, seed::Integer=gen_seed(UInt64)) r.x = splitmix64(seed % UInt64) r end @inline function rand(r::SplitMix64, ::Type{UInt64}) r.x = splitmix64(r.x) end @inline function splitmix64(x::UInt64) x += 0x9e3779b97f4a7c15 x = (x ⊻ (x >> 30)) * 0xbf58476d1ce4e5b9 x = (x ⊻ (x >> 27)) * 0x94d049bb133111eb x ⊻ (x >> 31) end init_seed(seed, ::Type{UInt64}) = splitmix64(seed % UInt64) function init_seed(seed, ::Type{UInt64}, N::Int) x = seed % UInt64 NTuple{N, UInt64}( x = splitmix64(x) for _ in 1:N ) end function init_seed(seed, ::Type{UInt32}, N::Int) x = seed % UInt64 NTuple{N, UInt32}(begin x = splitmix64(x) x % UInt32 end for _ in 1:N) end
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
2168
import Base: copy, copyto!, == import Random: rand, seed! import RandomNumbers: AbstractRNG, gen_seed, split_uint, seed_type """ ```julia AbstractXoroshiro128 <: AbstractRNG{UInt64} ``` The base abstract type for `Xoroshiro128`, `Xoroshiro128Star`, `Xoroshiro128Plus` and `Xoroshiro128StarStar`. """ abstract type AbstractXoroshiro128 <: AbstractRNG{UInt64} end for (star, plus, starstar) in ( (false, false, false), (true, false, false), (false, true, false), (false, false, true), ) rng_name = Symbol(string("Xoroshiro128", star ? "Star" : plus ? "Plus" : starstar ? "StarStar" : "")) @eval begin mutable struct $rng_name <: AbstractXoroshiro128 x::UInt64 y::UInt64 end function $rng_name(seed::NTuple{2, UInt64}=gen_seed(UInt64, 2)) r = $rng_name(zero(UInt64), zero(UInt64)) seed!(r, seed) r end $rng_name(seed::Integer) = $rng_name(init_seed(seed, UInt64, 2)) @inline function xorshift_next(r::$rng_name) $(plus ? :(p = r.x + r.y) : starstar ? :(p = xorshift_rotl(r.x * 5, 7) * 9) : nothing) s1 = r.y ⊻ r.x r.x = xorshift_rotl(r.x, 24) ⊻ s1 ⊻ (s1 << 16) r.y = xorshift_rotl(s1, 37) $(star ? :(r.y * 2685821657736338717) : (plus || starstar) ? :(p) : :(r.y)) end end end @inline seed_type(::Type{T}) where T <: AbstractXoroshiro128 = NTuple{2, UInt64} function copyto!(dest::T, src::T) where T <: AbstractXoroshiro128 dest.x = src.x dest.y = src.y dest end copy(src::T) where T <: AbstractXoroshiro128 = copyto!(T(), src) ==(r1::T, r2::T) where T <: AbstractXoroshiro128 = r1.x == r2.x && r1.y == r2.y seed!(r::AbstractXoroshiro128, seed::Integer) = seed!(r, split_uint(seed % UInt128)) function seed!(r::AbstractXoroshiro128, seed::NTuple{2, UInt64}=gen_seed(UInt64, 2)) all(==(0), seed) && error("0 cannot be the seed") r.x = seed[1] r.y = seed[2] xorshift_next(r) xorshift_next(r) r end @inline rand(r::AbstractXoroshiro128, ::Type{UInt64}) = xorshift_next(r)
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
1928
import Base: copy, copyto!, == import Random: rand, seed! import RandomNumbers: AbstractRNG, gen_seed, split_uint, seed_type """ ```julia AbstractXoroshiro64 <: AbstractRNG{UInt32} ``` The base abstract type for `Xoroshiro64Star` and `Xoroshiro64StarStar`. """ abstract type AbstractXoroshiro64 <: AbstractRNG{UInt32} end for (star, starstar) in ( (true, false), (false, true), ) rng_name = Symbol(string("Xoroshiro64", star ? "Star" : starstar ? "StarStar" : "")) @eval begin mutable struct $rng_name <: AbstractXoroshiro64 x::UInt32 y::UInt32 end function $rng_name(seed::NTuple{2, UInt32}=gen_seed(UInt32, 2)) r = $rng_name(zero(UInt32), zero(UInt32)) seed!(r, seed) r end $rng_name(seed::Integer) = $rng_name(init_seed(seed, UInt32, 2)) @inline function xorshift_next(r::$rng_name) p = r.x * 0x9E3779BB $(starstar ? :(p = xorshift_rotl(p, 5) * (5 % UInt32)) : nothing) s1 = r.y ⊻ r.x r.x = xorshift_rotl(r.x, 26) ⊻ s1 ⊻ (s1 << 9) r.y = xorshift_rotl(s1, 13) p end end end @inline seed_type(::Type{T}) where T <: AbstractXoroshiro64 = NTuple{2, UInt32} function copyto!(dest::T, src::T) where T <: AbstractXoroshiro64 dest.x = src.x dest.y = src.y dest end copy(src::T) where T <: AbstractXoroshiro64 = copyto!(T(), src) ==(r1::T, r2::T) where T <: AbstractXoroshiro64 = r1.x == r2.x && r1.y == r2.y seed!(r::AbstractXoroshiro64, seed::Integer) = seed!(r, split_uint(seed % UInt64)) function seed!(r::AbstractXoroshiro64, seed::NTuple{2, UInt32}=gen_seed(UInt32, 2)) all(==(0), seed) && error("0 cannot be the seed") r.x = seed[1] r.y = seed[2] xorshift_next(r) xorshift_next(r) r end @inline rand(r::AbstractXoroshiro64, ::Type{UInt32}) = xorshift_next(r)
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
3047
import Base: copy, copyto!, == import Random: rand, seed! import RandomNumbers: AbstractRNG, gen_seed, seed_type, unsafe_copyto!, unsafe_compare """ ```julia AbstractXorshift1024 <: AbstractRNG{UInt64} ``` The base abstract type for `Xorshift1024`, `Xorshift1024Star` and `Xorshift1024Plus`. """ abstract type AbstractXorshift1024 <: AbstractRNG{UInt64} end for (star, plus) in ( (false, false), (false, true), (true, false), ) rng_name = Symbol(string("Xorshift1024", star ? "Star" : plus ? "Plus" : "")) @eval begin mutable struct $rng_name <: AbstractXorshift1024 s0::UInt64 s1::UInt64 s2::UInt64 s3::UInt64 s4::UInt64 s5::UInt64 s6::UInt64 s7::UInt64 s8::UInt64 s9::UInt64 s10::UInt64 s11::UInt64 s12::UInt64 s13::UInt64 s14::UInt64 s15::UInt64 p::Int end function $rng_name(seed::NTuple{16, UInt64}=gen_seed(UInt64, 16)) o = zero(UInt64) r = $rng_name( o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, o, zero(Int) ) seed!(r, seed) r end function $rng_name(seed::Integer) $rng_name(init_seed(seed, UInt64, 16)) end @inline function xorshift_next(r::$rng_name) ptr = Ptr{UInt64}(pointer_from_objref(r)) p = r.p s0 = unsafe_load(ptr, p + 1) p = (p + 1) % 16 s1 = unsafe_load(ptr, p + 1) s1 ⊻= s1 << 31 s1 ⊻= s1 >> 11 s1 ⊻= s0 >> 30 s1 ⊻= s0 unsafe_store!(ptr, s1, p + 1) r.p = p $(star ? :(s1 * 2685821657736338717) : plus ? :(s1 + s0) : :s1) end end end @inline seed_type(::Type{T}) where T <: AbstractXorshift1024 = NTuple{16, UInt64} function copyto!(dest::T, src::T) where T <: AbstractXorshift1024 unsafe_copyto!(dest, src, UInt64, 16) dest.p = src.p dest end copy(src::T) where T <: AbstractXorshift1024 = copyto!(T(), src) ==(r1::T, r2::T) where T <: AbstractXorshift1024 = unsafe_compare(r1, r2, UInt64, 16) && r1.p == r2.p function seed!(r::AbstractXorshift1024, seed::NTuple{16, UInt64}) all(==(0), seed) && error("0 cannot be the seed") ptr = Ptr{UInt64}(pointer_from_objref(r)) @inbounds for i in 1:16 unsafe_store!(ptr, seed[i], i) end r.p = 0 for i in 1:16 xorshift_next(r) end r end function seed!(r::AbstractXorshift1024, seed::Integer...) l = length(seed) @assert 0 ≀ l ≀ 16 if l == 0 return seed!(r, gen_seed(UInt64, 16)) end seed = [x % UInt64 for x in seed] while length(seed) < 16 push!(seed, splitmix64(seed[end])) end seed!(r, Tuple(seed)) end @inline rand(r::AbstractXorshift1024, ::Type{UInt64}) = xorshift_next(r)
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
1904
import Base: copy, copyto!, == import Random: rand, seed! import RandomNumbers: AbstractRNG, gen_seed, split_uint, seed_type """ ```julia AbstractXorshift128 <: AbstractRNG{UInt64} ``` The base abstract type for `Xorshift128`, `Xorshift128Star` and `Xorshift128Plus`. """ abstract type AbstractXorshift128 <: AbstractRNG{UInt64} end for (star, plus) in ( (false, false), (false, true), (true, false), ) rng_name = Symbol(string("Xorshift128", star ? "Star" : plus ? "Plus" : "")) @eval begin mutable struct $rng_name <: AbstractXorshift128 x::UInt64 y::UInt64 end function $rng_name(seed::NTuple{2, UInt64}=gen_seed(UInt64, 2)) r = $rng_name(zero(UInt64), zero(UInt64)) seed!(r, seed) r end $rng_name(seed::Integer) = $rng_name(init_seed(seed, UInt64, 2)) @inline function xorshift_next(r::$rng_name) t = r.x ⊻ r.x << 23 r.x = r.y r.y = t ⊻ (t >> 3) ⊻ r.y ⊻ (r.y >> 24) $(star ? :(r.y * 2685821657736338717) : plus ? :(r.y + r.x) : :(r.y)) end end end @inline seed_type(::Type{T}) where T <: AbstractXorshift128 = NTuple{2, UInt64} function copyto!(dest::T, src::T) where T <: AbstractXorshift128 dest.x = src.x dest.y = src.y dest end copy(src::T) where T <: AbstractXorshift128 = copyto!(T(), src) ==(r1::T, r2::T) where T <: AbstractXorshift128 = r1.x == r2.x && r1.y == r2.y seed!(r::AbstractXorshift128, seed::Integer) = seed!(r, split_uint(seed % UInt128)) function seed!(r::AbstractXorshift128, seed::NTuple{2, UInt64}=gen_seed(UInt64, 2)) all(==(0), seed) && error("0 cannot be the seed") r.x = seed[1] r.y = seed[2] xorshift_next(r) xorshift_next(r) r end @inline rand(r::AbstractXorshift128, ::Type{UInt64}) = xorshift_next(r)
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
1455
import Base: copy, copyto!, == import Random: rand, seed! import RandomNumbers: AbstractRNG, gen_seed, seed_type """ ```julia AbstractXorshift64 <: AbstractRNG{UInt64} ``` The base abstract type for `Xorshift64` and `Xorshift64Star`. """ abstract type AbstractXorshift64 <: AbstractRNG{UInt64} end for star in (false, true) rng_name = Symbol(string("Xorshift64", star ? "Star" : "")) @eval begin mutable struct $rng_name <: AbstractXorshift64 x::UInt64 end function $rng_name(seed::Integer=gen_seed(UInt64)) r = $rng_name(zero(UInt64)) seed = init_seed(seed, UInt64) seed!(r, seed) r end @inline function xorshift_next(r::$rng_name) r.x ⊻= r.x << 18 r.x ⊻= r.x >> 31 r.x ⊻= r.x << 11 $(star ? :(r.x * 2685821657736338717) : :(r.x)) end end end @inline seed_type(::Type{T}) where T <: AbstractXorshift64 = UInt64 function copyto!(dest::T, src::T) where T <: AbstractXorshift64 dest.x = src.x dest end copy(src::T) where T <: AbstractXorshift64 = copyto!(T(), src) ==(r1::T, r2::T) where T <: AbstractXorshift64 = r1.x == r2.x function seed!(r::AbstractXorshift64, seed::Integer=gen_seed(UInt64)) seed == 0 && error("0 cannot be the seed") r.x = seed % UInt64 xorshift_next(r) r end @inline rand(r::AbstractXorshift64, ::Type{UInt64}) = xorshift_next(r)
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
2205
import Base: copy, copyto!, == import Random: rand, seed! import RandomNumbers: AbstractRNG, gen_seed, split_uint, seed_type """ ```julia AbstractXoshiro128 <: AbstractRNG{UInt32} ``` The base abstract type for `Xoshiro128Plus` and `Xoshiro128StarStar`. """ abstract type AbstractXoshiro128 <: AbstractRNG{UInt32} end for (plus, starstar) in ( (true, false), (false, true), ) rng_name = Symbol(string("Xoshiro128", plus ? "Plus" : starstar ? "StarStar" : "")) @eval begin mutable struct $rng_name <: AbstractXoshiro128 x::UInt32 y::UInt32 z::UInt32 w::UInt32 end function $rng_name(seed::NTuple{4, UInt32}=gen_seed(UInt32, 4)) o = zero(UInt32) r = $rng_name(o, o, o, o) seed!(r, seed) r end $rng_name(seed::Integer) = $rng_name(init_seed(seed, UInt32, 4)) @inline function xorshift_next(r::$rng_name) p = $(plus ? :(r.x + r.w) : starstar ? :(xorshift_rotl(r.x * (5 % UInt32), 7) * (9 % UInt32)) : nothing) t = r.y << 9 r.z ⊻= r.x r.w ⊻= r.y r.y ⊻= r.z r.x ⊻= r.w r.z ⊻= t r.w = xorshift_rotl(r.w, 11) p end end end @inline seed_type(::Type{T}) where T <: AbstractXoshiro128 = NTuple{4, UInt32} function copyto!(dest::T, src::T) where T <: AbstractXoshiro128 dest.x = src.x dest.y = src.y dest.z = src.z dest.w = src.w dest end copy(src::T) where T <: AbstractXoshiro128 = copyto!(T(), src) ==(r1::T, r2::T) where T <: AbstractXoshiro128 = r1.x == r2.x && r1.y == r2.y && r1.z == r2.z && r1.w == r2.w seed!(r::AbstractXoshiro128, seed::Integer) = seed!(r, split_uint(seed % UInt128, UInt32)) function seed!(r::AbstractXoshiro128, seed::NTuple{4, UInt32}=gen_seed(UInt32, 4)) all(==(0), seed) && error("0 cannot be the seed") r.x = seed[1] r.y = seed[2] r.z = seed[3] r.w = seed[4] xorshift_next(r) xorshift_next(r) xorshift_next(r) xorshift_next(r) r end @inline rand(r::AbstractXoshiro128, ::Type{UInt32}) = xorshift_next(r)
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
2238
import Base: copy, copyto!, == import Random: rand, seed! import RandomNumbers: AbstractRNG, gen_seed, split_uint, seed_type """ ```julia AbstractXoshiro256 <: AbstractRNG{UInt64} ``` The base abstract type for `Xoshiro256Plus` and `Xoshiro256StarStar`. """ abstract type AbstractXoshiro256 <: AbstractRNG{UInt64} end for (plus, starstar) in ( (true, false), (false, true), ) rng_name = Symbol(string("Xoshiro256", plus ? "Plus" : starstar ? "StarStar" : "")) @eval begin mutable struct $rng_name <: AbstractXoshiro256 x::UInt64 y::UInt64 z::UInt64 w::UInt64 end function $rng_name(seed::NTuple{4, UInt64}=gen_seed(UInt64, 4)) o = zero(UInt64) r = $rng_name(o, o, o, o) seed!(r, seed) r end $rng_name(seed::Integer) = $rng_name(init_seed(seed, UInt64, 4)) @inline function xorshift_next(r::$rng_name) p = $(plus ? :(r.x + r.w) : starstar ? :(xorshift_rotl(r.y * 5, 7) * 9) : nothing) # why here is r.y but in xoshiro128** is r.x? t = r.y << 17 r.z ⊻= r.x r.w ⊻= r.y r.y ⊻= r.z r.x ⊻= r.w r.z ⊻= t r.w = xorshift_rotl(r.w, 45) p end end end @inline seed_type(::Type{T}) where T <: AbstractXoshiro256 = NTuple{4, UInt64} function copyto!(dest::T, src::T) where T <: AbstractXoshiro256 dest.x = src.x dest.y = src.y dest.z = src.z dest.w = src.w dest end copy(src::T) where T <: AbstractXoshiro256 = copyto!(T(), src) ==(r1::T, r2::T) where T <: AbstractXoshiro256 = r1.x == r2.x && r1.y == r2.y && r1.z == r2.z && r1.w == r2.w seed!(r::AbstractXoshiro256, seed::Integer) = seed!(r, init_seed(seed, UInt64, 4)) function seed!(r::AbstractXoshiro256, seed::NTuple{4, UInt64}=gen_seed(UInt64, 4)) all(==(0), seed) && error("0 cannot be the seed") r.x = seed[1] r.y = seed[2] r.z = seed[3] r.w = seed[4] xorshift_next(r) xorshift_next(r) xorshift_next(r) xorshift_next(r) r end @inline rand(r::AbstractXoshiro256, ::Type{UInt64}) = xorshift_next(r)
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
510
using RandomNumbers import Random: seed! using Test: @test, @test_throws using Printf: @printf function compare_dirs(dir1::AbstractString, dir2::AbstractString) files1 = readdir(dir1) files2 = readdir(dir2) @test files1 == files2 for file in files1 file1 = joinpath(dir1, file) file2 = joinpath(dir2, file) lines1 = readlines(file1) lines2 = readlines(file2) @test lines1 == lines2 end end strip_cr(line::String) = replace(line, r"\r\n$" => "\n")
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
1398
using Test @testset "Generic functions" begin import Random: randn, randexp, bitrand, randstring, randsubseq, shuffle, randperm, randcycle @info "Testing Generic functions" r = PCG.PCGStateOneseq(123) @test randn(r) == -0.4957408739873887 @test randn(r, Float64, 8) == [ -0.38659391873108484, -0.12391575881839223, 0.305709506865529, 1.0234147128314572, 1.1925044460767074, 0.8448640519165571, -0.2982275988025108, 0.9615482011555472 ] @test randexp(r) == 1.0279939998988223 @test bitrand(r, 3, 3) == [false false false; false true false; false true true] # randstring method changed after a julia release randstringres = "" if VERSION >= v"1.5" randstringres = "6j22eD3r" else randstringres = "KuSFMMEc" end @test randstring(r) == randstringres a = 1:100 @test randsubseq(r, a, 0.1) == [1, 11, 12, 17, 19, 21, 27, 38, 44, 54, 58, 78, 80] a = 1:10 if VERSION >= v"1.11.0-DEV.57" @test shuffle(r, a) == [6, 8, 2, 5, 1, 10, 9, 4, 3, 7] @test randperm(r, 10) == [3, 10, 2, 6, 4, 1, 7, 8, 9, 5] else @test shuffle(r, a) == [3, 7, 5, 10, 2, 6, 1, 4, 9, 8] @test randperm(r, 10) == [2, 10, 1, 6, 4, 3, 7, 8, 9, 5] end @test randcycle(r, 10) == [8, 4, 5, 1, 10, 2, 3, 9, 7, 6] @test rand(r, ComplexF64) == 0.9500729643158807 + 0.9280185794620359im end
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
3839
using RandomNumbers using Test @testset "Check types" begin @test typeof(randfloat()) == Float64 @test typeof(randfloat(Float32)) == Float32 @test typeof(randfloat(Float64)) == Float64 @test typeof(randfloat(Float16)) == Float16 # arrays @test typeof(randfloat(Float16,2)) <: Vector{Float16} @test typeof(randfloat(Float32,2)) <: Vector{Float32} @test typeof(randfloat(Float64,2)) <: Vector{Float64} @test typeof(randfloat(Float16,2,3)) <: Matrix{Float16} @test typeof(randfloat(Float32,2,3)) <: Matrix{Float32} @test typeof(randfloat(Float64,2,3)) <: Matrix{Float64} end @testset "Non-default RNG" begin import RandomNumbers.Xorshifts.Xorshift64 rng = Xorshift64() @test typeof(randfloat(rng)) == Float64 @test typeof(randfloat(rng,Float16)) == Float16 @test typeof(randfloat(rng,Float32)) == Float32 @test typeof(randfloat(rng,Float64)) == Float64 # arrays @test typeof(randfloat(rng,Float16,2)) <: Vector{Float16} @test typeof(randfloat(rng,Float32,2)) <: Vector{Float32} @test typeof(randfloat(rng,Float64,2)) <: Vector{Float64} @test typeof(randfloat(rng,Float16,2,3)) <: Matrix{Float16} @test typeof(randfloat(rng,Float32,2,3)) <: Matrix{Float32} @test typeof(randfloat(rng,Float64,2,3)) <: Matrix{Float64} import RandomNumbers.MersenneTwisters.MT19937 rng = MT19937() @test typeof(randfloat(rng)) == Float64 @test typeof(randfloat(rng,Float16)) == Float16 @test typeof(randfloat(rng,Float32)) == Float32 @test typeof(randfloat(rng,Float64)) == Float64 # arrays @test typeof(randfloat(rng,Float16,2)) <: Vector{Float16} @test typeof(randfloat(rng,Float32,2)) <: Vector{Float32} @test typeof(randfloat(rng,Float64,2)) <: Vector{Float64} @test typeof(randfloat(rng,Float16,2,3)) <: Matrix{Float16} @test typeof(randfloat(rng,Float32,2,3)) <: Matrix{Float32} @test typeof(randfloat(rng,Float64,2,3)) <: Matrix{Float64} end @testset "Distribution is uniform [0,1) Float64" begin N = 100_000_000 x = randfloat(N) @test maximum(x) > 0.999999 @test minimum(x) < 1e-7 exponent_mask = 0x7ff0000000000000 exponent_bias = 1023 # histogram for exponents H = fill(0,64) for xi in x # 0.5 is in H[1], 0.25 is in H[2] etc e = reinterpret(UInt64,xi) & exponent_mask H[exponent_bias-Int(e >> 52)] += 1 end # test that the most frequent exponents occur at 50%, 25%, 12.5% etc. for i in 1:10 @test isapprox(H[i]/N,2.0^-i,atol=5e-4) end end @testset "Distribution is uniform [0,1) Float32" begin N = 100_000_000 x = randfloat(Float32,N) @test maximum(x) > prevfloat(1f0,5) @test minimum(x) < 1e-7 exponent_mask = 0x7f800000 exponent_bias = 127 # histogram for exponents H = fill(0,64) for xi in x # 0.5f0 is in H[1], 0.25f0 is in H[2] etc e = reinterpret(UInt32,xi) & exponent_mask H[exponent_bias-Int(e >> 23)] += 1 end # test that the most frequent exponents occur at 50%, 25%, 12.5% etc. for i in 1:10 @test isapprox(H[i]/N,2.0^-i,atol=5e-4) end end @testset "Distribution is uniform [0,1) Float16" begin N = 100_000_000 x = randfloat(Float16,N) @test maximum(x) == prevfloat(one(Float16)) @test minimum(x) == zero(Float16) # zero can be produced exponent_mask = 0x7c00 exponent_bias = 15 # histogram for exponents H = fill(0,16) for xi in x # 0.5f0 is in H[1], 0.25f0 is in H[2] etc e = reinterpret(UInt16,xi) & exponent_mask H[exponent_bias-Int(e >> 10)] += 1 end # test that the most frequent exponents occur at 50%, 25%, 12.5% etc. for i in 1:10 @test isapprox(H[i]/N,2.0^-i,atol=5e-4) end end
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
377
using Test @testset "RandomNumbers" begin for (i, testfile) in enumerate(( "generic.jl", "wrapped_rng.jl", "randfloat.jl", "PCG/runtests.jl", "MersenneTwisters/runtests.jl", "Xorshifts/runtests.jl")) @eval module $(Symbol("T$i")) include("common.jl") include($testfile) end end end
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
455
using Test @testset "WrappedRNG" begin using RandomNumbers.Xorshifts @info "Testing WrappedRNG" seed = RandomNumbers.gen_seed(UInt64, 2) r = Xoroshiro128(seed) r1 = WrappedRNG(r, UInt32) r2 = WrappedRNG(Xoroshiro128, UInt32, seed) @test rand(r1, UInt64) == rand(r2, UInt64) r3 = WrappedRNG(r2, UInt128) rand(r2, UInt64) @test rand(r3, UInt128) == rand(r2, UInt128) @test copyto!(copy(r1), r1) == r1 end
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
961
using Test if !@isdefined RandomNumbers include("../common.jl") end @testset "MersenneTwisters" begin using RandomNumbers.MersenneTwisters @info "Testing MersenneTwisters" stdout_ = stdout pwd_ = pwd() cd(dirname(@__FILE__)) rm("./actual"; force=true, recursive=true) mkpath("./actual") @test seed_type(MT19937) == NTuple{RandomNumbers.MersenneTwisters.N, UInt32} for mt_name in (:MT19937, ) outfile = open(string( "./actual/check-$(lowercase("$mt_name")).out" ), "w") redirect_stdout(outfile) @eval $mt_name() x = @eval $mt_name(123) @test copyto!(copy(x), x) == x for i in 1:100 @printf "%.9f\n" rand(x) end close(outfile) end redirect_stdout(stdout_) compare_dirs("expected", "actual") # Package content should not be modified. rm("./actual"; force=true, recursive=true) cd(pwd_) end
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
4053
using Test if !@isdefined RandomNumbers include("../common.jl") end @testset "PCG" begin using RandomNumbers.PCG @info "Testing PCG" stdout_ = stdout pwd_ = pwd() cd(dirname(@__FILE__)) rm("./actual"; force=true, recursive=true) mkpath("./actual") numbers = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'] suit = ['h', 'c', 'd', 's']; PCGStateOneseq() PCGStateOneseq(UInt32) PCGStateMCG() PCGStateMCG(UInt32) PCGStateSetseq() PCGStateSetseq(UInt32) PCGStateUnique() PCGStateUnique(UInt32) for (state_type_t, uint_type, method_symbol, return_type) in PCG_LIST state_type = eval(Symbol("PCGState$state_type_t")) method = Val{method_symbol} state_type(method) state_type(return_type, method) if state_type_t == :Setseq r = state_type(return_type, method, (42, 54)) @test seed_type(r) == NTuple{2, uint_type} else r = state_type(return_type, method, 42) @test seed_type(r) == uint_type end @test copyto!(copy(r), r) == r # Unique state won't produce the same sequence every time. if state_type_t == :Unique t = rand(r, return_type) advance!(r, -1) @test t == rand(r, return_type) bounded_rand(r, 200701281 % return_type) continue end outfile = open(string( "./actual/check-$(lowercase("$state_type_t"))-$(sizeof(uint_type) << 3)-", "$(replace(lowercase("$method_symbol"), "_" => "-"))-$(sizeof(return_type) << 3).out" ), "w") redirect_stdout(outfile) for round in 1:5 @printf "Round %d:\n" round @printf "%4dbit:" (sizeof(return_type) << 3) values = 10 wrap = 10 printstr = " 0x%04x" if return_type == UInt8 values, wrap, printstr = 14, 14, " 0x%02x" elseif return_type == UInt32 values, wrap, printstr = 6, 6, " 0x%08x" elseif return_type == UInt64 values, wrap, printstr = 6, 3, " 0x%016llx" elseif return_type == UInt128 values, wrap, printstr = 6, 2, " 0x%032llx" end for i in 1:values if i > 1 && (i - 1) % wrap == 0 @printf "\n\t" end value = rand(r, return_type) @eval @printf $printstr $value end @printf "\n" @printf " Again:" advance!(r, -(values % uint_type)) for i in 1:values if i > 1 && (i - 1) % wrap == 0 @printf "\n\t" end value = rand(r, return_type) @eval @printf $printstr $value end @printf "\n" @printf " Coins: " for i in 1:65 @printf "%c" (bounded_rand(r, 2 % return_type) == 1 ? 'H' : 'T') end @printf "\n" @printf " Rolls:" for i in 1:33 @printf " %d" (UInt32(bounded_rand(r, 6 % return_type)) + 1); end @printf "\n" cards = collect(0:51) for i = 52:-1:2 chosen = bounded_rand(r, i % return_type) card = cards[chosen+1] cards[chosen+1] = cards[i] cards[i] = card end @printf " Cards:" for i = 0:51 @printf " %c%c" numbers[(cards[i+1] Γ· 4)+1] suit[(cards[i+1] % 4)+1] if (i+1) % 22 == 0 @printf "\n\t" end end @printf "\n" @printf "\n" end close(outfile) end redirect_stdout(stdout_) compare_dirs("expected", "actual") # Package content should not be modified. rm("./actual"; force=true, recursive=true) cd(pwd_) end
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
code
2793
using Test if !@isdefined RandomNumbers include("../common.jl") end @testset "Xorshifts" begin using RandomNumbers.Xorshifts @info "Testing Xorshifts" stdout_ = stdout pwd_ = pwd() cd(dirname(@__FILE__)) rm("./actual"; force=true, recursive=true) mkpath("./actual") seeds = [0x1ed73cdc948901ab, 0x6d76dcf952161e22, 0x8d0eba5421bc695b, 0xa16065e26c36cce2, 0x944867a9aacc1bfa, 0x173d478b3ac9de91, 0x97becbc60ac9c1f2, 0x1b1cfeff0505b998, 0x815a28dc8372d7ab, 0x5c6746d45ae2c5c4, 0x17f22f9aa839c717, 0x1fd7e8194bb9c598, 0x442ffe4a57ed7987, 0xfd686ec417788eb6, 0x1ec96940807a8749, 0x64d93a8608a988ef] for (rng_name, seed_t) in ( (:SplitMix64, UInt64), (:Xoroshiro64Star, NTuple{2, UInt32}), (:Xoroshiro64StarStar, NTuple{2, UInt32}), (:Xoroshiro128Plus, NTuple{2, UInt64}), (:Xoroshiro128StarStar, NTuple{2, UInt64}), (:Xoshiro128Plus, NTuple{4, UInt32}), (:Xoshiro128StarStar, NTuple{4, UInt32}), (:Xoshiro256Plus, NTuple{4, UInt64}), (:Xoshiro256StarStar, NTuple{4, UInt64}), (:Xorshift64, UInt64), (:Xorshift64Star, UInt64), (:Xorshift128, NTuple{2, UInt64}), (:Xorshift128Star, NTuple{2, UInt64}), (:Xorshift128Plus, NTuple{2, UInt64}), (:Xorshift1024, NTuple{16, UInt64}), (:Xorshift1024Star, NTuple{16, UInt64}), (:Xorshift1024Plus, NTuple{16, UInt64}), (:Xoroshiro128, NTuple{2, UInt64}), (:Xoroshiro128Star, NTuple{2, UInt64}), ) outfile = open(string( "./actual/check-$(lowercase("$rng_name")).out" ), "w") redirect_stdout(outfile) rng_type = @eval Xorshifts.$rng_name x = rng_type() x = rng_type(1234) seed!(x, 2345) if rng_type == Xorshifts.SplitMix64 rng_type(0) else @test_throws( ErrorException("0 cannot be the seed"), seed!(x, seed_t <: Tuple ? (zeros(seed_t.types[1], length(seed_t.types))...,) : 0) ) end seed!(x) @test seed_type(x) == seed_t @test copyto!(copy(x), x) == x seed = seed_t <: Tuple ? ((seeds[i] % seed_t.types[i] for i in 1:length(seed_t.types))...,) : seeds[1] % seed_t x = rng_type(seed) for i in 1:100 @printf "%.9f\n" rand(x) end close(outfile) end redirect_stdout(stdout_) compare_dirs("expected", "actual") # Package content should not be modified. # rm("./actual"; force=true, recursive=true) cd(pwd_) end
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
docs
2302
# RandomNumbers.jl *Random number generators for the Julia language.* Build Status [![Build Status](https://github.com/JuliaRandom/RandomNumbers.jl/actions/workflows/ci.yml/badge.svg)](https://github.com/JuliaRandom/RandomNumbers.jl/actions/workflows/ci.yml) Code Coverage: [![codecov.io](https://codecov.io/github/JuliaRandom/RandomNumbers.jl/coverage.svg?branch=master)](https://codecov.io/github/JuliaRandom/RandomNumbers.jl?branch=master) Documentation: [![Stable Documentation](https://img.shields.io/badge/docs-stable-blue.svg)](https://juliarandom.github.io/RandomNumbers.jl/stable/) [![Devel Documentation](https://img.shields.io/badge/docs-dev-blue.svg)](https://juliarandom.github.io/RandomNumbers.jl/dev/) **RandomNumbers.jl** is a package of [Julia](http://julialang.org/), in which several random number generators (RNGs) are provided. If you use the Intel Math Kernel Library (MKL), [`VSL.jl`](https://github.com/JuliaRandom/VSL.jl) is also a good choice for random number generation. ## Installation This package is registered. The stable version of this package requires Julia `0.7+`. You can install it by: ```julia (v1.0) pkg> add RandomNumbers ``` It is recommended to run the test suites before using the package: ```julia (v1.0) pkg> test RandomNumbers ``` ## RNG Families There are four RNG families in this package: - [PCG](http://juliarandom.github.io/RandomNumbers.jl/stable/man/pcg/): A new family of RNG, based on *linear congruential generators*, using a *permuted function* to produce much more random output. - [Mersenne Twister](http://juliarandom.github.io/RandomNumbers.jl/stable/man/mersenne-twisters/): The most widely used RNG, with long period. - [Random123](http://juliarandom.github.io/RandomNumbers.jl/stable/man/random123/): A family of good-performance *counter-based* RNG. - [Xorshift](http://juliarandom.github.io/RandomNumbers.jl/stable/man/xorshifts/): A class of RNG based on *exclusive or* and *bit shift*. Note that `Random123` is now made a separate package as [Random123.jl](https://github.com/JuliaRandom/Random123.jl). ## Usage Please see the [documentation](http://juliarandom.github.io/RandomNumbers.jl/stable/man/basics/) for usage of this package. ## License This package is under [MIT License](./LICENSE.md).
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
docs
798
# TODO ## General - Redesign the framework of RNG in Julia Base. - `advance!` function whenever possible. - `copy` and `copyto!`. - Help improve `Distributions.jl`. ## PCG - Implement the extended version of PCG generators, which supports larger periods. - Figure out the performance issue of `PCG_XSH_RS`: it is expected to run faster than `PCG_RXS_M_XS`. ## Mersenne Twisters - Implement the 64-bit version of `MT19937`. ## Random123 - Make use of `CUDA` or `OpenCL`. - Improve the performance. - Store counters in a better way. ## Wrapped RNG - A function to be constructed from another `WrappedRNG`. ## Others - Perhaps consider implementing `arc4random` or `Chacha20`, which is slow but cryptographically secure. - Something like `seed_seq` in C++. - Test submodules separately.
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
docs
696
# RandomNumbers.jl Documentation **RandomNumbers.jl** is a collection of Random Number Generators for the Julia language. There are several kinds of RNG families in this package, provided as submodules. The examples and detailed descriptions of each RNG can be found on the Manual pages. ## Manual Outline ```@contents Pages = [ "man/basics.md", "man/benchmark.md", "man/pcg.md", "man/mersenne-twisters.md", "man/random123.md", "man/xorshifts.md", "man/ref.md", ] Depth = 2 ``` ## Library Outline ```@contents Pages = [ "lib/random-numbers.md", "lib/pcg.md", "lib/mersenne-twisters.md", "lib/random123.md", "lib/xorshifts.md", ] Depth = 2 ```
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
docs
251
# MersenneTwisters ## Index ```@index Pages = ["mersenne-twisters.md"] ``` ## Public ```@autodocs Modules = [RandomNumbers.MersenneTwisters] Private = false ``` ## Internal ```@autodocs Modules = [RandomNumbers.MersenneTwisters] Public = false ```
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
docs
198
# PCG ## Index ```@index Pages = ["pcg.md"] ``` ## Public ```@autodocs Modules = [RandomNumbers.PCG] Private = false ``` ## Internal ```@autodocs Modules = [RandomNumbers.PCG] Public = false ```
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
docs
1679
# RandomNumbers ## Index ```@index Pages = ["random-numbers.md"] ``` ## [Common Functions](@id common-functions) - [Base.rand](https://docs.julialang.org/en/v1/stdlib/Random/#Base.rand) - [Random.rand!](https://docs.julialang.org/en/v1/stdlib/Random/#Random.rand!) - [Random.seed!](https://docs.julialang.org/en/v1/stdlib/Random/#Random.seed!) - [Base.randn](https://docs.julialang.org/en/v1/stdlib/Random/#Base.randn) - [Random.randn!](https://docs.julialang.org/en/v1/stdlib/Random/#Random.randn!) - [Random.randexp](https://docs.julialang.org/en/v1/stdlib/Random/#Random.randexp) - [Random.randexp!](https://docs.julialang.org/en/v1/stdlib/Random/#Random.randexp!) - [Random.bitrand](https://docs.julialang.org/en/v1/stdlib/Random/#Random.bitrand) - [Random.randstring](https://docs.julialang.org/en/v1/stdlib/Random/#Random.randstring) - [Random.randsubseq](https://docs.julialang.org/en/v1/stdlib/Random/#Random.randsubseq) - [Random.randsubseq!](https://docs.julialang.org/en/v1/stdlib/Random/#Random.randsubseq!) - [Random.randperm](https://docs.julialang.org/en/v1/stdlib/Random/#Random.randperm) - [Random.randperm!](https://docs.julialang.org/en/v1/stdlib/Random/#Random.randperm!) - [Random.randcycle](https://docs.julialang.org/en/v1/stdlib/Random/#Random.randcycle) - [Random.randcycle!](https://docs.julialang.org/en/v1/stdlib/Random/#Random.randcycle!) - [Random.shuffle](https://docs.julialang.org/en/v1/stdlib/Random/#Random.shuffle) - [Random.shuffle!](https://docs.julialang.org/en/v1/stdlib/Random/#Random.shuffle!) ## Public ```@autodocs Modules = [RandomNumbers] Private = false ``` ## Internal ```@autodocs Modules = [RandomNumbers] Public = false ```
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
docs
222
# Random123 ## Index ```@index Pages = ["random123.md"] ``` ## Public ```@autodocs Modules = [RandomNumbers.Random123] Private = false ``` ## Internal ```@autodocs Modules = [RandomNumbers.Random123] Public = false ```
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
docs
222
# Xorshifts ## Index ```@index Pages = ["xorshifts.md"] ``` ## Public ```@autodocs Modules = [RandomNumbers.Xorshifts] Private = false ``` ## Internal ```@autodocs Modules = [RandomNumbers.Xorshifts] Public = false ```
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
docs
8595
# Basics This page describes basic concepts and fundamental knowledge of **RandomNumbers.jl**. !!! note Unless otherwise specified, all the random number generators in this package are *pseudorandom* number generators (or *deterministic* random bit generator), which means they only provide numbers whose properties approximate the properties of *truly random* numbers. Always, especially in secure-sensitive cases, keep in mind that they do not gaurantee a totally random performance. ## Installation This package is registered. The stable version of this package requires Julia `0.7+`. You can install it by: ```julia (v1.0) pkg> add RandomNumbers ``` It is recommended to run the test suites before using the package: ```julia (v1.0) pkg> test RandomNumbers ``` ## Interface First of all, to use a RNG from this package, you can import `RandomNumbers.jl` and use RNG by declare its submodule's name, or directly import the submodule. Then you can create a random number generator of certain type. For example: ```julia julia> using RandomNumbers julia> r = Xorshifts.Xorshift1024Plus() ``` or ```julia julia> using RandomNumbers.Xorshifts julia> r = Xorshift1024Plus() ``` The submodules have some API in common and a few differently. All the Random Number Generators (RNGs) are child types of `AbstractRNG{T}`, which is a child type of `Base.Random.AbstractRNG` and replaces it. (`Base.Random` may be refactored sometime, anyway.) The type parameter `T` indicates the original output type of a RNG, and it is usually a child type of `Unsigned`, such as `UInt64`, `UInt32`, etc. Users can change the output type of a certain RNG type by use a wrapped type: [`WrappedRNG`](@ref). Consistent to what `Base.Random` does, there are generic functions: - `seed!(::AbstractRNG{T}[, seed])` initializes a RNG by one or a sequence of numbers (called *seed*). The output sequences by two RNGs of the same type should be the same if they are initialized by the same seed, which makes them *deterministic*. The seed type of each RNG type can be different, you can refer to the corresponding manual pages for details. If no `seed` provided, then it will use [`RandomNumbers.gen_seed`](@ref) to get a "truly" random one. - `rand(::AbstractRNG{T}[, ::Type{TP}=Float64])` returns a random number in the type `TP`. `TP` is usually an `Unsigned` type, and the return value is expected to be uniformly distributed in {0, 1} at every bit. When `TP` is `Float64` (as default), this function returns a `Float64` value that is expected to be uniformly distributed in ``[0, 1)``. The discussion about this is in the [Conversion to Float](@ref) section. The other common functions such as `rand(::AbstractRNG, ::Dims)` and `rand!(::AbstractRNG, ::AbstractArray)`, and the ones that generate random numbers in a certain distribution such as `randn`, `randexp`, `randcycle`, etc. defined in the standard library `Random` still work well. See the [official docs](https://docs.julialang.org/en/latest/stdlib/Random/) for details. You can also refer to [this section](@ref common-functions) for the common functions. The constructors of all the types of RNG are designed to take the same kind of parameters as `seed!`. For example: ```jldoctest julia> using RandomNumbers.Xorshifts julia> import Random: rand! julia> r1 = Xorshift128Star(123) # Create a RNG of Xorshift128Star with the seed "123" Xorshift128Star(0x000000003a300074, 0x000000003a30004e) julia> r2 = Xorshift128Star(); # Use a random value to be the seed. julia> rand(r1) # Generate a number uniformly distributed in ``[0, 1)``. 0.2552720033868119 julia> A = rand(r1, UInt64, 2, 3) # Generate a 2x3 matrix `A` in `UInt64` type. 2Γ—3 Array{UInt64,2}: 0xbed3dea863c65407 0x607f5f9815f515af 0x807289d8f9847407 0x4ab80d43269335ee 0xf78b56ada11ea641 0xc2306a55acfb4aaa julia> rand!(r1, A) # Refill `A` with random numbers. 2Γ—3 Array{UInt64,2}: 0xf729352e2a72b541 0xe89948b5582a85f0 0x8a95ebd6aa34fcf4 0xc0c5a8df4c1b160f 0x8b5269ed6c790e08 0x930b89985ae0c865 ``` People will get the same results in their own computers of the above lines. For more interfaces and usage examples, please refer to the manual pages of each RNG. ## Empirical Statistical Testing Empirical statistical testing is very important for random number generation, because the theoretical mathematical analysis is insufficient to verify the performance of a random number generator. The famous and highly evaluated [**TestU01** library](http://simul.iro.umontreal.ca/testu01/tu01.html) is chosen to test the RNGs in `RandomNumbers.jl`. **TestU01** offers a collection of test suites, and *Big Crush* is the largest and most stringent test battery for empirical testing (which usually takes several hours to run). *Big Crush* has revealed a number of flaws of lots of well-used generators, even including the *Mersenne Twister* (or to be more exact, the *dSFMT*) which is currently used in `Base.Random` as GLOBAL_RAND`.[^1] This package chooses [RNGTest.jl](https://github.com/andreasnoack/RNGTest.jl) to use TestU01. The testing results are available on [Benchmark](@ref) page. [^1]: [`rand` fails bigcrush #6464](https://github.com/JuliaLang/julia/issues/6464) ## Conversion to Float Besides the statistical flaws, popular generators often neglect the importance of converting unsigned integers to floating numbers. The most common situation is to convert an `UInt` to a `Float64` which is uniformly distributed in ``[0.0, 1.0)``. For example, neither the `std::uniform_real_distribution` in libstdc++ from gcc, libc++ from llvm, nor the standard library from MSVC has a correct performance, as they all have a non-zero probability for generating the max value which is an open bound and should not be produced. The cause is that a `Float64` number in ``[0.0, 1.0)`` has only 53 *significand* bits (52 explicitly stored), which means at least 11 bits of an `UInt64` are abandoned when being converted to `Float64`. If using the naive approach to multiply an `UInt64` by ``2^{-64}``, users may get 1.0, and the distribution is not good (although using ``2^{-32}`` for an `UInt32` is OK). In this package, we make use of the fact that the distribution of the least 52 bits can be the same in an `UInt64` and a `Float64` (if you are familiar with [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point) this is easy to understand). An `UInt64` will firstly be converted to a `Float64` that is perfectly uniformly distributed in [1.0, 2.0), and then subtract one. This is a very fast approach, but not completely ideal, as the statistics of the least significant bits are affected. Due to rounding in the subtraction, - the least significant bit of `rand()` is always 0, the second last is only at 25% a 1, the third last bit is at 37.5% chance a 1, the n-th last bit is at p=1/2-2^(-n) chance a 1. In practice, this only affects the last few bits, but holds for `rand(Float32)` as well as for `rand(Float64)`. - the sampling is not from all floats in [0,1) but only from 2^23 (Float32) or 2^52 (Float64). - The subset of floats which is sampled from is every second float in [1/2,1), every 4th in [1/4,1/2), so every 2n-th in [1/2n,1/n). - The smallest positive float (but note that 0f0/0.0 is also possible) that is sampled is `eps(Float32)=1.1920929f-7` (Float32) or `eps(Float64)=2.220446049250313e-16` (Float64). The current default RNG in `Base.Random` library does the same thing, so it also causes some tricky problems.[^2] To address some of these issues RandomNumbers.jl also provides `randfloat()` for `Float16`, `Float32` and `Float64`, which - has full entropy for all significant bits, i.e. 0 and 1 always occur at 50% chance - samples from all floats in [2.7105054f-20,1) (Float32) and [2.710505431213761e-20,1) (Float64) and true [0,1) (Float16, including correct chances for subnormals) - As the true chance to obtain a 0 in [0,1) for floats is effectively 0, it is practically also 0 for randfloat (except for Float16). - is about 20% slower than `rand`, see [#72](https://github.com/sunoru/RandomNumbers.jl/issues/72) `randfloat()` is not based on the `[1,2) minus one`-approach but counts the leading zeros of a random `UInt` to obtain the correct chances for the exponent bits (which are 50% for 01111110 meaning [1/2,1) in float32, 25% for 01111101 meaning [1/4,1/2), etc.). This is combined with random `UInt` bits for the significand. [^2]: [Least significant bit of rand() is always zero #16344](https://github.com/JuliaLang/julia/issues/16344)
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
docs
3074
# Benchmark ```@meta CurrentModule = RandomNumbers ``` This page includes the results of speed tests and big crush tests of several kinds of RNGs in this package. The data is produced on such a computer: ```julia julia> versioninfo() Julia Version 0.5.0-rc0+0 Commit 633443c (2016-08-02 00:53 UTC) Platform Info: System: Linux (x86_64-redhat-linux) CPU: Intel(R) Core(TM) i5-3470 CPU @ 3.20GHz WORD_SIZE: 64 BLAS: libopenblas (USE64BITINT DYNAMIC_ARCH NO_AFFINITY Sandybridge) LAPACK: libopenblas64_ LIBM: libopenlibm LLVM: libLLVM-3.7.1 (ORCJIT, ivybridge) ``` All the benchmark scripts are in the [benchmark](https://github.com/sunoru/RandomNumbers.jl/tree/master/benchmark) directory, you can do the tests by yourself. !!!note All the data here is only for reference, and will be updated as this package is updated. ## Speed Test The speed test results are as following (the smaller is the better): ![Speed Test](./img/speed_test.svg) and detailed in the table (sorted by speed): |RNG Type|Speed (ns/64 bits)|RNG Type|Speed (ns/64 bits)|RNG Type|Speed (ns/64 bits)| |---|:-:|---|:-:|---|:-:| |Xoroshiro128Star|1.184|PCG\_XSL\_RR\_128|2.646|Philox4x64|5.737| |Xorshift128Plus|1.189|PCG\_XSH\_RS\_64|2.738|Threefry4x64|5.965| |Xoroshiro128Plus|1.393|PCG\_XSH\_RR\_128|3.260|Threefry2x64|7.760| |Xorshift128Star|1.486|PCG\_XSL\_RR\_64|3.308|Philox2x32|9.698| |PCG\_RXS\_M\_XS\_64|1.522|PCG\_XSH\_RS\_128|3.373|Philox4x32|11.517| |PCG\_XSL\_RR\_RR\_128|1.602|PCG\_RXS\_M\_XS\_32|3.420|Threefry4x32|12.241| |Xorshift64|1.918|PCG\_XSH\_RR\_64|3.580|Threefry2x32|16.253| |BaseMT19937\*|1.971|Xorshift1024Plus|3.725|ARS1x128|17.081| |Xorshift64Star|2.000|Xorshift1024Star|3.748|ARS4x32|18.059| |PCG\_XSL\_RR\_RR\_64|2.044|MT19937|4.229|AESNI1x128|18.304| |PCG\_RXS\_M\_XS\_128|2.482|Philox2x64|5.161|AESNI4x32|29.770| \*`BaseMT19937` denotes to `Base.Random.MersenneTwister`. ## Big Crush Test 10 kinds of RNGs (which are worth considering) have been tested with Big Crush test batteries: |RNG Type|Speed (ns/64 bits)|Total CPU time|Failed Test(s)\*| |---|:-:|:-:|---| |AESNI1x128|18.304|04:14:22.19| | |ARS1x128|17.081|04:13:27.54|55 SampleCorr, k = 1 p-value = 7.0e-4| |BaseMT19937|1.971|03:18:23.47| | |MT19937|4.229|03:32:59.06|36 Gap, r = 0 p-value = eps<br>80LinearComp, r = 0 p-value = 1-eps1<br>81 LinearComp, r = 29 p-value = 1-eps1| |PCG\_RXS\_M\_XS\_64\_64|1.522|03:20:07.97| | |PCG\_XSH\_RS\_128\_64|3.373|03:24:57.54|54 SampleMean, r = 10 0.9991| |Philox2x64|5.737|03:28:52.27|35 Gap, r = 25 3.4e-4| |Threefry2x64|5.965|03:37:53.53| | |Xoroshiro128Plus|1.393|03:33:16.51| | |Xorshift1024Star|3.748|03:39:15.19| | \*eps means a value < 1.0e-300, and eps1 means a value < 1.0e-15. It is interesting that BaseMT19937 passes all the tests when generating `UInt64` (by generating two `UInt32` with dSFMT). The PCG ones do not pass all the tests as the paper says, but the failures are just near the threshold. The RNG with best performance here is `Xoroshiro128Plus`, which passes all the tests and has an excellent speed.
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
docs
3423
# Mersenne Twisters ```@meta CurrentModule = RandomNumbers.MersenneTwisters DocTestSetup = quote using RandomNumbers.MersenneTwisters r = MT19937(Tuple(UInt32(i) for i in 1:624)) end ``` The **Mersenne Twister**[^1] is so far the most widely used PRNG. Mersenne Twisters are taken as default random number generators of a great many of software systems, including the Julia language until the current 1.0 version. The most commonly used version of Mersenne Twisters is **MT19937**, which has a very long period of ``2^{19937}-1`` and passes numerous tests including the Diehard tests. However, it also has many flaws by today's standards. For the large period, MT19937 has to use a 2.5 KiB state buffer, which place a load on the memory caches. More severely, it cannot pass all the TestU01 statistical tests[^2], and the speed is not so fast. **So it is not recommended in most situations.** The [`MersenneTwisters`](@ref) in this package currently only provides one RNG: [`MT19937`](@ref). `MT19937` can only produce `UInt32` numbers as output. Its state is an array of 624 `UInt32` numbers, so it takes 624 `UInt32`s as seed. A default function is also provided to deal with one `UInt32` as seed. ## Examples To use the Mersenne Twisters, firstly import the module: ```jldoctest julia> using RandomNumbers.MersenneTwisters ``` A certain sequence can be used to initialize an instance of MT19937: ```jldoctest julia> seed = Tuple(UInt32(i) for i in 1:624); # This is a Tuple of 1..624 julia> r = MT19937(seed); ``` Since MT19937 is a RNG based on linear-feedback shift-register techniques, this approach is not recommended for an obivous reason: ```jldoctest julia> rand(r, UInt32, 10) 10-element Array{UInt32,1}: 0x23864fee 0xdd51a593 0x20c049a2 0xde17a3df 0x20804931 0xde57a34c 0x20c049a0 0xde17a3dd 0x20804933 0xde57a34e ``` The firstly generated numbers are so poorly random. This is because the most bits of states are zeros. So it is better to create a `MT19937` in this way: ```jldoctest julia> r = MT19937(); ``` In this case, all the 624 states will be filled with truly random numbers produced by `RandomDevice`. If someone needs the reproducibility, just save the state `r.mt` and use it for next time. An initialization function described in the original paper[^1] is also implemented here, so the seed can also be just one `UInt32` number (or an `Integer` whose least 32 bits will be truncated): ```jldoctest julia> import Random julia> Random.seed!(r, 0xabcdef12); julia> rand(r, UInt32, 10) 10-element Array{UInt32,1}: 0x986c5150 0xbb9e20f5 0xfb59a25a 0x189eb49c 0xbcca5395 0x48d9fdf5 0x3193f581 0xe0b6d080 0x63154ca2 0x72b28f0d ``` Note that if you use one `UInt32` number as seed, you will always get in a bias way.[^3] [^1]: Matsumoto M, Nishimura T. Mersenne twister: a 623-dimensionally equidistributed uniform pseudo-random number generator[J]. ACM Transactions on Modeling and Computer Simulation (TOMACS), 1998, 8(1): 3-30. doi:[10.1145/272991.272995](https://dx.doi.org/10.1145/272991.272995). [^2]: L'Ecuyer P, Simard R. TestU01: AC library for empirical testing of random number generators[J]. ACM Transactions on Mathematical Software (TOMS), 2007, 33(4): 22. doi:[10.1145/1268776.1268777](http://dx.doi.org/10.1145/1268776.1268777) [^3]: [C++ Seeding Surprises](http://www.pcg-random.org/posts/cpp-seeding-surprises.html)
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
docs
4074
# PCG Family ```@meta CurrentModule = RandomNumbers.PCG DocTestSetup = quote using RandomNumbers.PCG r = PCGStateOneseq(1234567) end ``` **[Permuted Congruential Generators](http://www.pcg-random.org/)** (PCGs) are a family of RNGs which uses a *linear congruential generator* as the state-transition function, and uses *permutation functions on tuples* to produce output that is much more random than the RNG's internal state.[^1] ## PCG Type Each PCG generator is available in four variants, based on how it applies the additive constant for its underlying LCG; the variations are: - [`PCGStateOneseq`](@ref) (single stream): all instances use the same fixed constant, thus the RNG always somewhere in same sequence. - [`PCGStateMCG`](@ref) (mcg): adds zero, resulting in a single stream and reduced period. - [`PCGStateSetseq`](@ref) (specific stream): the constant can be changed at any time, selecting a different random sequence. - [`PCGStateUnique`](@ref) (unique stream): the constant is based on the memory address of the object, thus every RNG has its own unique sequence. ## PCG Method Type - [`PCG_XSH_RS`](@ref): high xorshift, followed by a random shift. It's fast and is a good performer. - [`PCG_XSH_RR`](@ref): high xorshift, followed by a random rotate. It's fast and is a good performer. Slightly better statistically than `PCG_XSH_RS`. - [`PCG_RXS_M_XS`](@ref): fixed xorshift (to low bits), random rotate. The most statistically powerful generator, but all those steps make it slower than some of the others. (but in this package the benchmark shows it's even fast than `PCG_XSH_RS`, which is an current issue.) - [`PCG_XSL_RR`](@ref): fixed xorshift (to low bits), random rotate. Useful for 128-bit types that are split across two CPU registers. - [`PCG_XSL_RR_RR`](@ref): fixed xorshift (to low bits), random rotate (both parts). Useful for 128-bit types that are split across two CPU registers. Use this in need of an invertable 128-bit RNG. ## Interface and Examples An instance of PCG generator can be created by specify the state type, the output type, the method and seed. When seed is missing it is set to truly random numbers. The default output type is `UInt64`, and the default method is `PCG_XSH_RS`. The seed will be converted to the internal state type (a kind of unsigned integer), and for PCGs with specific stream (`PCGStateSetseq`) the seed should be a `Tuple` of two `Integer`s. Note that not all parameter combinations are available (see [`PCG_LIST`](@ref)). For example: ```jldoctest julia> using RandomNumbers.PCG julia> PCGStateOneseq(UInt64, 1234567) # create a single stream PCG, specifying the output type and seed. PCGStateOneseq{UInt128,Val{:XSH_RS},UInt64}(0xa10d40ffc2b1e573e589b22b2450d1fd) julia> PCGStateUnique(PCG_RXS_M_XS, 1234567); # unique stream PCG, specifying the method and seed. julia> PCGStateSetseq(UInt32, PCG_XSH_RR, (1234567, 7654321)) PCGStateSetseq{UInt64,Val{:XSH_RR},UInt32}(0xfc77de2cd901ff85, 0x0000000000e99763) ``` [`bounded_rand`](@ref) is provided by this module, in which the bound is must an integer in the output type: ```jldoctest julia> r = PCGStateOneseq(1234567) PCGStateOneseq{UInt128,Val{:XSH_RS},UInt64}(0xa10d40ffc2b1e573e589b22b2450d1fd) julia> [bounded_rand(r, UInt64(100)) for i in 1:6] 6-element Array{UInt64,1}: 0x0000000000000012 0x000000000000000a 0x000000000000002e 0x0000000000000049 0x0000000000000043 0x000000000000002b ``` PCG also has an [`advance!`](@ref) function, used to advance the state of a PCG instance. ```jldoctest julia> import Random julia> Random.seed!(r, 1234567); julia> rand(r, 4) 4-element Array{Float64,1}: 0.5716257379273757 0.9945058856417783 0.8886220302794352 0.08763836824057081 julia> advance!(r, -4); julia> rand(r, 4) 4-element Array{Float64,1}: 0.5716257379273757 0.9945058856417783 0.8886220302794352 0.08763836824057081 ``` [^1]: O’NEILL M E. PCG: A Family of Simple Fast Space-Efficient Statistically Good Algorithms for Random Number Generation[J].
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
docs
4529
# Random123 Family ```@meta CurrentModule = Random123 DocTestSetup = quote using Random123 end ``` **[Random123](https://www.deshawresearch.com/resources_random123.html)** is a library of "counter-based" random number generators (CBRNGs), developed by D.E.Shaw Research[^1]. *Counter-based* means the RNGs in this family can produce the ``\mathrm{N}^\textrm{th}`` number by applying a stateless mixing function to the *counter* ``\mathrm{N}``, instead of the conventional approach of using ``\mathrm{N}`` iterations of a stateful transformation. The current version of Random123 in this package is 1.09, and there are four kinds of RNGs: [Threefry](@ref), [Philox](@ref), [AESNI](@ref), [ARS](@ref). The original paper[^1] says all the RNGs in Random123 can pass Big Crush in TestU01, but in the [benchmark](@ref Benchmark) we did, `ARS1x128` and `Philox2x64` have a slight failure. ## Random123 RNGs All the RNG types in Random123 have a property `ctr1`, which denotes to its first *counter*, and some of them have `ctr2` for the second *counter*. The suffix '-1x', '-2x' and '-4x' indicates how many numbers will be generated per time. The first one or two or four properties of a RNG type in Random123 are always `x`(or `x1`, `x2`, etc.), which denote to the produced numbers. ### Threefry `Threefry` is a **non-cryptographic** adaptation of the Threefish block cipher from the [Skein Hash Function](http://www.skein-hash.info/). In this package, there are two `Type`s of `Threefry`: [`Threefry4x`](@ref) and [`Threefry2x`](@ref). Besides the output type `T`, there is another parameter `R`, which denotes to the number of rounds, and must be at least 1 and no more than 32. With 20 rounds (by default), `Threefry` has a considerable safety margin over the minimum number of rounds with no known statistical flaws, but still has excellent performance. They both support `UInt32` and `UInt64` output. ### Philox `Philox` uses a Feistel network and integer multiplication. `Philox` also has two `Type`s: [`Philox4x`](@ref) and [`Philox2x`](@ref). The number of rounds must be at least 1 and no more than 16. With 10 rounds (by default), Philox2x32 has a considerable safety margin over the minimum number of rounds with no known statistical flaws, but still has excellent performance. They both support `UInt32` and `UInt64` output. ### AESNI `AESNI` uses the Advanced Encryption Standard (AES) New Instruction, available on certain modern x86 processors (some models of Intel Westmere and Sandy Bridge, and AMD Interlagos, as of 2011). AESNI CBRNGs can operate on `UInt128` type. `AESNI` has two `Type`s: [`AESNI1x`](@ref) and [`AESNI4x`](@ref). `AESNI4x` only internally converts `UInt128` to `UInt32`. ### ARS `ARS` (Advanced Randomization System) is a **non-cryptographic** simplification of [AESNI](@ref). `ARS` has two `Type`s: [`ARS1x`](@ref) and [`ARS4x`](@ref). `ARS4x` only internally converts `UInt128` to `UInt32`. Note that although it uses some cryptographic primitives, `ARS1x` uses a cryptographically weak key schedule and is **not** suitable for cryptographic use. The number of rounds must be at least 1 and no more than 10, and is 7 by default. ## Examples For detailed usage of each RNG, please refer to the [library docs](@ref Random123). To use Random123, firstly import the module: ```julia julia> using Random123 ``` Take `Philox4x64` for example: ```jldoctest julia> r = Philox4x(); # will output UInt64 by default, and two seed integers are truly randomly produced. julia> r = Philox4x((0x12345678abcdef01, 0x10fedcba87654321)); # specify the seed. julia> r = Philox4x(UInt64, (0x12345678abcdef01, 0x10fedcba87654321)); # specify both the output type and seed. julia> rand(r, NTuple{4, UInt64}) (0x00d626ee85b7d2ed, 0xa57b4af2b68c655e, 0x82dad737de789de2, 0x8d390e05845e6c4d) julia> set_counter!(r, 123); # update the counter manually. julia> rand(r, UInt64, 4) 4-element Array{UInt64,1}: 0x56a4eb812faa9cd7 0xf3d3464a49b23b56 0xda5a5824aea0b2bb 0x097a8d117a2bb20a julia> set_counter!(r, 0); julia> rand(r, NTuple{4, UInt64}) (0x00d626ee85b7d2ed, 0xa57b4af2b68c655e, 0x82dad737de789de2, 0x8d390e05845e6c4d) ``` [^1]: John K. Salmon, Mark A. Moraes, Ron O. Dror, and David E. Shaw, "Parallel Random Numbers: As Easy as 1, 2, 3," Proceedings of the International Conference for High Performance Computing, Networking, Storage and Analysis (SC11), New York, NY: ACM, 2011. doi:[10.1145/2063384.2063405](http://dx.doi.org/10.1145/2063384.2063405)
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
1.6.0
c6ec94d2aaba1ab2ff983052cf6a606ca5985902
docs
2949
# Xorshift Family ```@meta CurrentModule = RandomNumbers.Xorshifts ``` [`Xorshift`](http://xoroshiro.di.unimi.it/) family is a class of PRNGs based on linear transformation that takes the *exclusive or* of a number with a *bit-shifted* version of itself[^1]. They are extremely fast on mordern computer architectures, and are very suitable for non-cryptographically-secure use. The suffix `-Star` and `-Plus` in the RNG names denote to two classes of improved RNGs[^2][^3], which make it to pass Big Crush in TestU01. `-Star` RNGs are obtained by scrambling the output of a normal `Xorshift` generator with a 64-bit invertible multiplier, while `-Plus` RNGs return the sum of two consecutive output of a `Xorshift` generator. In this package there are four series of RNG types: - [`Xorshift64`](@ref) and [`Xorshift64Star`](@ref): They have a period of ``2^{64}``, but not recommended because 64 bits of state are not enough for any serious purpose. - [`Xorshift128`](@ref), [`Xorshift128Star`](@ref) and [`Xorshift128Plus`](@ref): They have a period of ``2^{128}``. `Xorshift128Plus` is presently used in the JavaScript engines of Chrome, Firefox and Safari. - [`Xorshift1024`](@ref), [`Xorshift1024Star`](@ref) and [`Xorshift1024Plus`](@ref): They have a long period of ``2^{1024}``, and takes some more space for storing the state. If you are running large-scale parallel simulations, it's a good choice to use `Xorshift1024Star`. - [`Xoroshiro128`](@ref), [`Xoroshiro128Star`](@ref) and [`Xoroshiro128Plus`](@ref): The successor to `Xorshift128` series. They make use of a carefully handcrafted shift/rotate-based linear transformation, resulting in a significant improvement in speed and in statistical quality. Therefore, `Xoroshiro128Plus` is the current best suggestion for replacing other low-quality generators. ```@meta CurrentModule = RandomNumbers ``` All the RNG types produce `UInt64` numbers, if you have need for other output type, see [`WrappedRNG`](@ref). ## Examples The usage of `Xorshift` family is very simple and common: ```jldoctest julia> using RandomNumbers.Xorshifts julia> r = Xoroshiro128Plus(); # create a RNG with truly random seed. julia> r = Xoroshiro128Plus(0x1234567890abcdef) # with a certain seed. Note that the seed must be non-zero. Xoroshiro128Plus(0xe7eb72d97b4beac6, 0x9b86d56534ba1f9e) julia> rand(r) 0.14263790854661185 julia> rand(r, UInt32) 0x0a0315b3 ``` [^1]: Marsaglia G. Xorshift rngs[J]. Journal of Statistical Software, 2003, 8(14): 1-6. doi:[10.18637/jss.v008.i14](http://dx.doi.org/10.18637/jss.v008.i14) [^2]: Vigna S. An experimental exploration of Marsaglia's xorshift generators, scrambled[J]. arXiv preprint [arXiv:1402.6246](http://arxiv.org/abs/1402.6246), 2014. [^3]: Vigna S. Further scramblings of Marsaglia's xorshift generators[J]. arXiv preprint [arXiv:1404.0390](http://arxiv.org/abs/1404.0390), 2014.
RandomNumbers
https://github.com/JuliaRandom/RandomNumbers.jl.git
[ "MIT" ]
0.1.0
db8fc65f9f6c34cfc54743501925bb72d0e74b92
code
354
using Documenter, makedocs( modules = [], format = Documenter.HTML(; prettyurls = get(ENV, "CI", nothing) == "true"), authors = "jishnub", sitename = ".jl", pages = Any["index.md"] # strict = true, # clean = true, # checkdocs = :exports, ) deploydocs( repo = "github.com/jishnub/.jl.git", push_preview = true )
IrrationalExpressions
https://github.com/jishnub/IrrationalExpressions.jl.git
[ "MIT" ]
0.1.0
db8fc65f9f6c34cfc54743501925bb72d0e74b92
code
1891
""" A module that makes expressions like `-Ο€` behave like Irrational, rather than Float64. Generates IrrationalExpr objects when arithmetic operations are applied to objects of type Irrational, and these operations are carried out in the destination type when type conversion occurs. For example, `BigFloat(Ο€) + BigFloat(-Ο€)` will evaluate to BigFloat(0), rather than to approximately 1.2e-16. """ module IrrationalExpressions import Base: +, -, *, /, convert, promote_rule, show struct IrrationalExpr{op, N} <: Real args::NTuple{N,Union{IrrationalExpr, Irrational, Rational, Integer}} end @generated convert(::Type{T}, x::IrrationalExpr{op,N}) where {T<:AbstractFloat,op,N} = Expr(:call, op, [Expr(:call, :convert, T, :( x.args[$i] )) for i=1:N]...) promote_rule(::Type{T1}, ::Type{T2}) where {T1<:AbstractFloat, T2<:IrrationalExpr}= T1 promote_rule(::Type{BigFloat}, ::Type{T2}) where {T2<:IrrationalExpr} = BigFloat ## Unary operators (+)(x::IrrationalExpr) = x (-)(x::IrrationalExpr) = IrrationalExpr{:(-),1}((x,)) (-)(x::Irrational) = IrrationalExpr{:(-),1}((x,)) ## Binary operators ops = (:(+), :(-), :(*), :(/)) types = (IrrationalExpr, Irrational, Rational, Integer) for op in ops, i in eachindex(types), j in eachindex(types) if i<=2 || j<=2 @eval $op(x::$(types[i]), y::$(types[j])) = IrrationalExpr{Symbol($op),2}((x,y)) end end # We define expr() as a conveninent middle step to get to strings, # but this also allows eval(expr(x)) as a roundabout way to get x. expr(x) = x expr(::Irrational{sym}) where {sym} = sym expr(x::IrrationalExpr{op,N}) where {op,N} = Expr(:call, op, map(expr,x.args)...) show(io::IO, x::IrrationalExpr) = print(io, string(expr(x)), " = ", string(convert(Float64,x))[1:end-2], "...") for T in (:AbstractFloat,:BigFloat,:Float64,:Float32,:Float16) eval(quote Base.$T(x::IrrationalExpr) = convert($T,x) end) end end # module
IrrationalExpressions
https://github.com/jishnub/IrrationalExpressions.jl.git
[ "MIT" ]
0.1.0
db8fc65f9f6c34cfc54743501925bb72d0e74b92
code
575
using IrrationalExpressions using Test @test BigFloat(-Ο€) == -BigFloat(Ο€) @test BigFloat(-(-Ο€)) == BigFloat(Ο€) @test BigFloat(2Ο€+1//3) == BigFloat(2)*BigFloat(Ο€)+BigFloat(1//3) @test isa(Ο€, Irrational) @test isa(Ο€+1, IrrationalExpressions.IrrationalExpr) @test isa(Ο€+1.0, Float64) @test isa(2Ο€+1.0, Float64) @test isa(Ο€+BigFloat(1), BigFloat) @test +(1+Ο€) == 1+Ο€ @test string(1+pi) == "1 + Ο€ = 4.1415926535897..." @test string(2Ο€+0.0) == "6.283185307179586" @test string(2Ο€+BigFloat(0)) == "6.283185307179586476925286766559005768394338798750211641949889184615632812572396"
IrrationalExpressions
https://github.com/jishnub/IrrationalExpressions.jl.git
[ "MIT" ]
0.1.0
db8fc65f9f6c34cfc54743501925bb72d0e74b92
code
363
#### #### Coverage summary, printed as "(percentage) covered". #### #### Useful for CI environments that just want a summary (eg a Gitlab setup). #### using Coverage cd(joinpath(@__DIR__, "..", "..")) do covered_lines, total_lines = get_summary(process_folder()) percentage = covered_lines / total_lines * 100 println("($(percentage)%) covered") end
IrrationalExpressions
https://github.com/jishnub/IrrationalExpressions.jl.git
[ "MIT" ]
0.1.0
db8fc65f9f6c34cfc54743501925bb72d0e74b92
code
266
# only push coverage from one bot get(ENV, "TRAVIS_OS_NAME", nothing) == "linux" || exit(0) get(ENV, "TRAVIS_JULIA_VERSION", nothing) == "1.3" || exit(0) using Coverage cd(joinpath(@__DIR__, "..", "..")) do Codecov.submit(Codecov.process_folder()) end
IrrationalExpressions
https://github.com/jishnub/IrrationalExpressions.jl.git
[ "MIT" ]
0.1.0
db8fc65f9f6c34cfc54743501925bb72d0e74b92
docs
3721
# IrrationalExpressions.jl [![Build Status](https://travis-ci.com/jishnub/IrrationalExpressions.jl.svg?branch=master)](https://travis-ci.com/jishnub/IrrationalExpressions.jl) [![Coverage Status](https://coveralls.io/repos/github/jishnub/IrrationalExpressions.jl/badge.svg?branch=master)](https://coveralls.io/github/jishnub/IrrationalExpressions.jl?branch=master) [![codecov](https://codecov.io/gh/jishnub/IrrationalExpressions.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/jishnub/IrrationalExpressions.jl) IrrationalExpressions is a Julia module that makes expressions like `2Ο€` behave as irrational numbers, rather than `Float64`. ## The Problem Julia has a few irrational constants, like `Ο€` and `e`. Arbitrary precision packages, like BigFloat, may provide conversion methods that yield these constants with the desired precision. However, any arithmetic operation that happens before conversion defaults to `Float64`. ``` julia> BigFloat(Ο€) + BigFloat(-Ο€) 1.224646799147353177226065932275001058209749445923078164062861980294536250318213e-16 julia> typeof(-Ο€) Float64 ``` This may lead to subtle bugs. For example, `2Ο€*x` will only be correct to about 16 decimal places, even if `x` has higher precision. It must be written as `2(Ο€*x)` in order to get the precision of `x`. ## The Solution Using the `IrrationalExpressions` module, arithmetic operations don't immediately force conversion to Float64. Instead the expression is kept unevaluated until the target type is known. ``` julia> using IrrationalExpressions julia> -pi -Ο€ = -3.1415926535897... julia> BigFloat(Ο€) + BigFloat(-Ο€) 0.0 ``` ## Supported Operations `+`, `-`, `*` and `/` are currently supported. Downconversion occurs when a floating point value is encountered. The resulting type is that of the floating point value. ``` julia> Ο„ = 2Ο€ 2Ο€ = 6.2831853071795... julia> Ο„ + 0.0 6.283185307179586 julia> Ο„ + BigFloat(0) 6.283185307179586476925286766559005768394338798750211641949889184615632812572396 ``` Functions in `Base` typically convert to `Float64` when encountering an unknown subtype of `Real`. They will work as usual. ``` julia> cos(2Ο€) 1.0 julia> typeof(ans) Float64 ``` ## Supported Types `Integer`, `Rational` and `Irrational` can be used to build irrational expressions. Care must be taken so that floats are not accidentally created. `(1//2)Ο€` is an `IrrationalExpr`, but `(1/2)Ο€` is a `Float64`. New floating-point types need not explicitly support conversion from `IrrationalExpr`. Any subtype of `AbstractFloat` that has conversions from `Integer`, `Rational` and `Irrational`, promotion from `Real` and the necessary arithmetic operations is automatically supported. ## Caveat Because this is a quick hack, there's no simplification, or elimination of common subexpressions. If irrational expressions are inadvertently created in a loop, they can grow exponentially ``` julia> a = Ο€; for i=1:5; global a = a-a/3; end; a ((((Ο€ - Ο€ / 3) - (Ο€ - Ο€ / 3) / 3) - ((Ο€ - Ο€ / 3) - (Ο€ - Ο€ / 3) / 3) / 3) - (((Ο€ - Ο€ / 3) - (Ο€ - Ο€ / 3) / 3) - ((Ο€ - Ο€ / 3) - (Ο€ - Ο€ / 3) / 3) / 3) / 3) - ((((Ο€ - Ο€ / 3) - (Ο€ - Ο€ / 3) / 3) - ((Ο€ - Ο€ / 3) - (Ο€ - Ο€ / 3) / 3) / 3) - (((Ο€ - Ο€ / 3) - (Ο€ - Ο€ / 3) / 3) - ((Ο€ - Ο€ / 3) - (Ο€ - Ο€ / 3) / 3) / 3) / 3) / 3 = 0.41370767454680... ``` (The work-around is to convert to the desired floating-point type before entering the loop.) ## To-Do-List * There needs to be some way to keep expressions from blowing up in a loop. At minimum, the size should be tracked, and an error thrown at some point. * It would be possible to extend this to things like `sqrt(Integer)`, `Integer^Rational`, etc. * Support for complex-valued irrational expressions, like `pi * im` is still missing.
IrrationalExpressions
https://github.com/jishnub/IrrationalExpressions.jl.git
[ "MIT" ]
0.1.0
db8fc65f9f6c34cfc54743501925bb72d0e74b92
docs
31
# *Documentation goes here.*
IrrationalExpressions
https://github.com/jishnub/IrrationalExpressions.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
891
using TypeClasses using Documenter DocMeta.setdocmeta!(TypeClasses, :DocTestSetup, :(using TypeClasses); recursive=true) makedocs(; modules=[TypeClasses], authors="Stephan Sahm <stephan.sahm@gmx.de> and contributors", repo="https://github.com/JuliaFunctional/TypeClasses.jl/blob/{commit}{path}#{line}", sitename="TypeClasses.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://JuliaFunctional.github.io/TypeClasses.jl", assets=String[], ), pages=[ "Home" => "index.md", "Manual" => [ "Introduction" => "manual.md", "TypeClasses" => "manual-TypeClasses.md", "DataTypes" => "manual-DataTypes.md", ], "Library" => "library.md", ], ) deploydocs(; repo="github.com/JuliaFunctional/TypeClasses.jl", devbranch="main", )
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
2210
# TODO add Foldable class to refer to the reduce, foldr, foldl? module TypeClasses export neutral, combine, βŠ•, reduce_monoid, foldr_monoid, foldl_monoid, orelse, ⊘, foreach, @syntax_foreach, map, @syntax_map, pure, ap, curry, mapn, @mapn, tupled, neutral_applicative, combine_applicative, orelse_applicative, flatmap, flatten, β† , @syntax_flatmap, flip_types using Compat using Reexport using Requires using Monadic export @pure # a user only needs @pure from Monadi @reexport using DataTypesBasic include("Utils/Utils.jl") using .Utils include("DataTypes/DataTypes.jl") @reexport using .DataTypes # TypeClasses # =========== # (they may already include default implementations in terms of other typeclasses) # we decided for a flat module without submodules to simplify overloading the functions include("TypeClasses/MonoidAlternative.jl") include("TypeClasses/FunctorApplicativeMonad.jl") include("TypeClasses/FlipTypes.jl") # depends on both Monoid and Applicative # TODO add Arrow typeclass (composition) # Instances # ========= include("TypeInstances/AbstractVector.jl") include("TypeInstances/Callable.jl") include("TypeInstances/Dict.jl") include("TypeInstances/Future.jl") include("TypeInstances/Iterable.jl") # only supplies default functions, no actual dispatch is done (Reason: there had been too many conflicts with Dict already) include("TypeInstances/Monoid.jl") include("TypeInstances/Pair.jl") include("TypeInstances/State.jl") include("TypeInstances/String.jl") include("TypeInstances/Task.jl") include("TypeInstances/Tuple.jl") include("TypeInstances/Writer.jl") include("TypeInstances_DataTypesBasic/Const.jl") include("TypeInstances_DataTypesBasic/Identity.jl") include("TypeInstances_DataTypesBasic/Either.jl") include("TypeInstances_DataTypesBasic/MultipleExceptions.jl") include("TypeInstances_DataTypesBasic/ContextManager.jl") # extra interactions between ContainerTypes include("convert.jl") function __init__() # there are known issues with require. See this issue for updates https://github.com/JuliaLang/Pkg.jl/issues/1285 @require Dictionaries="85a47980-9c8c-11e8-2b9f-f7ca1fa99fb4" include("TypeInstances/AbstractDictionary.jl") end end # module
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
1858
# We support some convenient converts for interaction between Containers # converting Writer to other Containers # ------------------------------------- # we just forget the acc # this is destructive, hence we throw a warning function Base.convert(::Type{<:Identity}, x::Writer) @warn "Forgetting Writter.acc = $(x.acc) where Writer.value = $(x.value)." Identity(x.value) end function Base.convert(T::Type{<:AbstractArray}, x::Writer) @warn "Forgetting Writter.acc = $(x.acc) where Writer.value = $(x.value)." convert(Base.typename(T).wrapper, [x.value]) end function Base.convert(::Type{<:ContextManager}, x::Writer) @warn "Forgetting Writter.acc = $(x.acc) where Writer.value = $(x.value)." @ContextManager cont -> cont(x.value) end # Converting other Containers to Writer # ------------------------------------- # construct acc via neutral function Base.convert(::Type{<:Writer{Acc}}, x::ContextManager) where Acc Writer(neutral(Acc), x(identity)) end function Base.convert(::Type{<:Writer{Acc}}, x::Identity) where Acc Writer(neutral(Acc), x.value) end # AbstractArray # ------------- # we cannot support Array/Vector, as there is no way to get several values in to the one Writer.value # we also do not need to support conversion to Iterable because the flatmap of Iterable just expects the Base.iterate interface, which exists for Vector # Iterables # --------- # conversion methods for convenience function Base.convert(T::Type{<:AbstractArray}, iter::Iterable) @assert(Base.IteratorSize(iter) isa Union{Base.HasLength, Base.HasShape}, "Cannot convert possibly infinite Iterable to Vector") convert(Base.typename(T).wrapper, collect(iter)) end # we don't need to convert anything to Iterable for interoperability, as Iterables use `iterate` for flatmap # hence everything which defines `iterate` automatically works
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
187
""" wrapper to clearly indicate that something should be treated as a Callable """ struct Callable{F} f::F end (callable::Callable)(args...; kwargs...) = callable.f(args...;kwargs...)
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
243
module DataTypes export Iterable, Callable, Writer, getaccumulator, State, getstate, putstate include("Iterables.jl") using .Iterables include("Callable.jl") include("Writers.jl") using .Writers include("States.jl") using .States end
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
1877
# DEPRECATED, no longer needed module Iterables export IterateEmpty, IterateSingleton, Iterable import ProxyInterfaces using DataTypesBasic using TypeClasses.Utils # Iterable Wrapper # ================ # TODO get rid of TypeTag ElemType """ wrapper to clearly indicate that something should be treated as an Iterable """ struct Iterable{IterType} iter::IterType # we follow the naming of Base.Generator end Iterable() = Iterable(IterateEmpty()) # empty iter Iterable(it::Iterable) = it # don't nest Iterable wrappers ProxyInterfaces.iterator(::Type{Iterable{IterT}}) where {IterT} = IterT ProxyInterfaces.iterator(it::Iterable) = it.iter ProxyInterfaces.@iterator Iterable # includes map # generic convert method Base.convert(::Type{Iterable{T}}, x::Iterable{T}) where T = x function Base.convert(::Type{<:Iterable}, x) @assert(isiterable(x), "Only iterables can be converted to Iterable, please overload `Base.isiterable` respectively") Iterable(x) end # Iterable Helpers # ================ struct IterateEmpty{ElType} end # Union{} makes most sense as default type, as it has no element at all # also typeinference should work correctly as `promote_type(Union{}, Int) == Int` IterateEmpty() = IterateEmpty{Union{}}() Base.iterate(::IterateEmpty) = nothing Base.IteratorSize(::Type{<:IterateEmpty}) = Base.HasLength() Base.length(::IterateEmpty) = 0 Base.IteratorEltype(::Type{<:IterateEmpty}) = Base.HasEltype() Base.eltype(::Type{IterateEmpty{T}}) where T = T struct IterateSingleton{T} value::T end Base.iterate(iter::IterateSingleton) = iter.value, nothing Base.iterate(iter::IterateSingleton, state) = nothing Base.IteratorSize(::Type{<:IterateSingleton}) = Base.HasLength() Base.length(::IterateSingleton) = 1 Base.IteratorEltype(::Type{<:IterateSingleton}) = Base.HasEltype() Base.eltype(::Type{IterateSingleton{T}}) where T = T end # module
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
1436
module States export State, getstate, putstate """ State(func) State() do state .... return value, newstate end State monad, which capsulate a state within a monadic type for monadic encapsulation of the state-handling. You can run a state by either calling it, or by using `Base.run`. If no initial state is given, `nothing` is used. """ struct State{T} "s -> (a, s)" func::T end # running a State function (s::State)(state = nothing) s.func(state) end Base.run(state::State, initial_state = nothing) = state(initial_state) @doc raw""" getstate Standard value for returning the hidden state of the `State` Monad. Examples -------- ```jldoctest julia> using TypeClasses julia> mystate = @syntax_flatmap begin state = getstate @pure println("state = $state") end; julia> mystate(42) state = 42 (nothing, 42) ``` """ const getstate = State() do state state, state end @doc raw""" putstate(x) `putstate` is a standard constructor for `State` objects which changes the underlying state to the given value. Examples -------- ```jldoctest julia> using TypeClasses julia> mystate = @syntax_flatmap begin putstate(10) state = getstate @pure println("The state is $state, and should be 10") end; julia> mystate() The state is 10, and should be 10 (nothing, 10) ``` """ putstate(x) = State() do state (), x end end # module
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
877
module Writers export Writer, getaccumulator using StructEquality using TypeClasses using DataTypesBasic """ like Pair, however assumes that `combine` is defined for the accumulator `acc` Note that `neutral` may indeed be undefined """ struct Writer{Acc, Value} acc::Acc value::Value function Writer(acc, value=nothing) new{typeof(acc), typeof(value)}(acc, value) end end @def_structequal Writer """ getaccumulator(writer::Writer) Returns the accumulator of the Writer value. Examples -------- ```jldoctest julia> using TypeClasses julia> getaccumulator(Writer("example-accumulator")) "example-accumulator" ``` """ getaccumulator(writer::Writer) = writer.acc Base.get(writer::Writer) = writer.value Base.getindex(writer::Writer) = writer.value Base.eltype(::Type{Writer{Acc, T}}) where {Acc, T} = T Base.eltype(::Type{<:Writer}) = Any end # module
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
1584
using TypeClasses.Utils """ flip_types(value::T{S{A}})::S{T{A}} reverses the two outer containers, e.g. making an Array of Options into an Option of an Array. """ function flip_types end """ default_flip_types_having_pure_combine_apEltype(container) Use this helper function to ease the definition of `flip_types` for your own type. Note that the following interfaces are assumed: - iterable - pure - combine - ap on eltype And in case of empty iterable in addition the following: - neutral - pure on eltype We do not overload `flip_types` directly because this would require dispatching on whether `isAp(eltype(T))`. But relying on `eltype` to define different semantics is strongly discouraged. """ function default_flip_types_having_pure_combine_apEltype(iter::T) where T first = iterate(iter) if first === nothing # only in this case we actually need `pure(eltype(T))` and `neutral(T)` # for non-empty sequences everything works for Types without both pure(eltype(T), neutral(T)) else b, state = first # we need to abstract out details so that combine can actually work # note that because of its definition, pure(ABC, x) == pure(A, x) # start = feltype_unionall_implementationdetails(fmap(traitsof, a -> pure(traitsof, T, a), x)) # we can only combine on S start = map(c -> pure(T, c), b) # we can only combine on ABC Base.foldl(Iterators.rest(iter, state); init = start) do acc, b mapn(acc, b) do accβ€², c # working in applicative context B accβ€² βŠ• pure(T, c) # combining on T end end end end
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
10969
using Monadic using ExprParsers import Base: foreach, map, eltype """ foreach(f, functor) Like map, but destroying the context. I.e. makes only sense for functions with side effects map, flatmap and foreach should have same semantics. Note that this does not work for all Functors (e.g. not for Callables), however is handy in many cases. This is also the reason why we don't use the default fallback to map, as this may make no sense for your custom Functor. """ """ @syntax_foreach begin # Vectors behaves like nested for loops within @syntax_foreach a = [1, 2, 3] b = [10, 20] @pure a + b end # [[11, 21], [12, 22], [13, 23]] This is a variant of the monadic syntax which uses `foreach` for both map_like and flatmap_like. See `Monadic.@monadic` for more details. """ macro syntax_foreach(block::Expr) block = macroexpand(__module__, block) esc(monadic(:(TypeClasses.foreach), :(TypeClasses.foreach), block)) end macro syntax_foreach(wrapper, block::Expr) block = macroexpand(__module__, block) esc(monadic(:(TypeClasses.foreach), :(TypeClasses.foreach), wrapper, block)) end # Functor # ======= """ map(f, functor) The core functionality of a functor, applying a normal function "into" the context defined by the functor. Think of map and vector as best examples. """ """ @syntax_map begin # Vectors behave similar to nested for loops within @syntax_map a = [1, 2, 3] b = [10, 20] @pure a + b end # [[11, 21], [12, 22], [13, 23]] This is a variant of the monadic syntax which uses `map` for both map_like and flatmap_like. See `Monadic.@monadic` for more details. """ macro syntax_map(block::Expr) block = macroexpand(__module__, block) esc(monadic(:(TypeClasses.map), :(TypeClasses.map), block)) end macro syntax_map(wrapper, block::Expr) esc(monadic(:(TypeClasses.map), :(TypeClasses.map), wrapper, block)) end # Applicative # =========== """ pure(T::Type, a) wraps value a into container T """ function pure end """ ap(f::F1, a::F2) -> F3 Apply function in container `F1` to element in container `F2`, returning results in the same container `F3`. The default implementation uses `flatmap` and `map`, so that in general only those two need to be defined. """ function ap(f, a) default_ap_having_map_flatmap(f, a) end # basic functionality # ------------------- """ @mapn f(a, b, c, d) translates to mapn(f, a, b, c, d) """ macro mapn(call_expr) parsed = parse_expr(EP.Call(), call_expr) @assert isempty(parsed.kwargs) "mapn does not support keyword arguments, but found $(parsed.kwargs)." callee = if isempty(parsed.curlies) parsed.name else :($(parsed.name){($(parsed.curlies...))}) end esc(:(TypeClasses.mapn($callee, $(parsed.args...)))) end # generic implementation, looping over the arguments # - - - - - - - - - - - - - - - - - - - - - - - - - - # because of world problem we cannot call eval in curry (see e.g. https://discourse.julialang.org/t/running-in-world-age-x-while-current-world-is-y-errors/5871/3) # hence we define it logically by collecting all args function curry(func, n::Int) function h(x, prev_xs) new_xs = tuple(prev_xs..., x) if length(new_xs) == n func(new_xs...) else x -> h(x, new_xs) end end x -> h(x, ()) end # Note that the try to make this a generative function failed because of erros like # """ERROR: The function body AST defined by this @generated function is not pure. This likely means it contains a closure or comprehension.""" """ mapn(f, a1::F{T1}, a2::F{T2}, a3::F{T3}, ...) -> F{T} Apply a function over applicative contexts instead of plain values. Similar to `Base.map`, however sometimes the semantic differs slightly. `TypeClasses.mapn` always follows the semantics of `TypeClasses.flatmap` if defined. E.g. for `Base.Vector` the `Base.map` function zips the inputs and checks for same length. On the other hand `TypeClasses.mapn` combines all combinations of inputs instead of the zip (which conforms with the semantics of flattening nested Vectors). """ function mapn(func, args...) n = length(args) if n == 0 error("mapn is not defined for 0 args as the type T needed for pure(T, x) is not known") else cfunc = curry(func, n) Base.foldl((f, a) -> ap(f, a), args[2:end]; init = map(cfunc, args[1])) end end # specifically compiled versions # - - - - - - - - - - - - - - - # We compile specific versions for specific numbers of arguments via code generation. # Tests showed that this leads way more optimal code. # Note, that it is not possible to do this with generated functions, as the resulting expression needs to curry # the function, which requires closures, however they are not supported within generated function bodies. function _create_curried_expr(func, N::Int) args_symbols = Symbol.(:a, 1:N) final_call = :($func($(args_symbols...))) foldr(args_symbols, init=final_call) do a, subfunc :($a -> $subfunc) end end function _create_ap_expr(curried_func, args_symbols) @assert length(args_symbols) >= 1 first_applied = :(map($curried_func, $(args_symbols[1]))) foldl(args_symbols[2:end], init=first_applied) do partially_applied, a :(ap($partially_applied, $a)) end end for N in 1:128 # 128 is an arbitrary number func_name = :func args_symbols = Symbol.(:a, 1:N) curried_func_name = :curried_func curried_func_expr = _create_curried_expr(func_name, N) ap_expr = _create_ap_expr(curried_func_name, args_symbols) @eval function mapn($func_name, $(args_symbols...)) $curried_func_name = $curried_func_expr $ap_expr end end # common applications of mapn # - - - - - - - - - - - - - - """ tupled(Option(1), Option(2), Option(3)) == Option((1,2,3)) tupled(Option(1), None, Option(3)) == None Combine several Applicative contexts by building up a Tuple """ function tupled(applicatives...) mapn(tuple, applicatives...) end # default implementations # ----------------------- # default implementations collide to often with other traits definitions and rather do harm than good # hence we just give a default definition which can be used for custom definitions default_map_having_ap_pure(f, a::A) where {A} = ap(pure(A, f), a) # generic Monoid implementations for Applicative # ---------------------------------------------- # it is tempting to overload `neutral`, `combine` and so forth directly, # however dispatching on eltype is not allowed if used for different semantics, as the element-type is an unstable property of a return value, so it should not lead to different results the one or the other way. function neutral_applicative(T::Type) pure(T, neutral(eltype(T))) end function combine_applicative(a, b) mapn(βŠ•, a, b) end function orelse_applicative(a, b) mapn(orelse, a, b) end # Monad # ===== # we use flatmap instead of flatten as the default function, because of the following reasons: # - flatmap has a similar signature as map and ap, and hence should fit more intuitively into the overal picture for beginners # - flatmap is what is most often used in e.g. `@syntax_flatmap`, and hence this should optimal code # - flatten seams to have more information about the nested types, however as julia's typeinference is incomplete # and may not correctly infer subtypes, it is actually quite tricky to dispatch correctly on nested typevariables. # Concretely you want the functionality to not differ whether typeinference worked or not, and hence you have # To deal with Vector{Any} and similar missing typeinformation on the typeparameters. You can fix the types, # but you always have to be careful that you do so. # And of course this approach only works for containers where you actually have a proper `eltype`. # A last point to raise is that not dispatching on nested Functors prevents the possibility of flattening # multiple different Functors. This is partly, however the same result can be achieved much better using # ExtensibleEffects. # Hence we don't see any real use of complex nested dispatch any longer and recommend rather not to use it # because of the unintuitive complexity. """ flatmap(function_returning_A, a::A)::A `flatmap` applies a function to a container and immediately flattens it out. While map would give you `A{A{...}}`, flatmap gives you a plain `A{...}`, without any nesting. If you define your own versions of flatmap, the recommendation is to apply a `Base.convert` after applying `f`. This makes sure your flatmap is typesafe, and actually enables sound interactions with other types which may be convertable to your A. E.g. for Vector the implementation looks as follows: ``` TypeClasses.flatmap(f, v::Vector) = vcat((convert(Vector, f(x)) for x in v)...) ``` """ function flatmap end # basic functionality # ------------------- """ flatten(::A{A})::A = flatmap(identity, a) `flatten` gets rid of one level of nesting. Has a default fallback to use `flatmap`. """ flatten(a) = flatmap(identity, a) """ a β†  b = flatmap(_ -> b, a) # \\twoheadrightarrow A convenience operator for monads which just applies the second monad within the first one. The operator β†  (\\twoheadrightarrow) is choosen because the other favourite ≫ (\\gg) which would have been in accordance with [haskell unicode syntax for monads](https://hackage.haskell.org/package/base-unicode-symbols-0.2.4.2/docs/Control-Monad-Unicode.html) is unfortunately parsed as boolean comparison with extra semantics which leads to errors with non-boolean applications. β†  is just the most similar looking other operator which does not have this restriction and is right-associative. """ a β†  b = flatmap(_ -> b, a) # right associative β† (a, b, more...) = a β†  b β†  foldr(β† , more) # more is non-empty, as the case `a β†  b` is always defined """ @syntax_flatmap begin # Vector behave similar to nested for loops within @syntax_flatmap a = [1, 2, 3] b = [10, 20] @pure a + b end # [11, 21, 12, 22, 13, 23] This is the standard monadic syntax which uses `map` for map_like and `flatmap` for flatmap_like. See `Monadic.@monadic` for more details. """ macro syntax_flatmap(block::Expr) block = macroexpand(__module__, block) esc(monadic(:(TypeClasses.map), :(TypeClasses.flatmap), block)) end macro syntax_flatmap(wrapper, block::Expr) block = macroexpand(__module__, block) esc(monadic(:(TypeClasses.map), :(TypeClasses.flatmap), wrapper, block)) end # Now can define the fallback definition for ap with monad style # ============================================================== # we don't overwrite `ap` directly because it can easily conflict with custom definitions # instead it is offered as a default definition which you can use for your custom type # for monadic code we actually don't need Pure default_ap_having_map_flatmap(f, a) = @syntax_flatmap begin f = f a = a @pure f(a) end
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
3296
# Monoid / Semigroup # ================== """ neutral neutral(::Type) neutral(_default_return_value) = neutral Neutral element for `βŠ•`, also called "identity element". `neutral` is a function which can give you the neutral element for a concrete type, or alternatively you can use it as a singleton value which combines with everything. By default `neutral(type)` will return the generic `neutral` singleton. You can override it for your specific type to have a more specific neutral value. We decided for name `neutral` according to https://en.wikipedia.org/wiki/Identity_element. Alternatives seem inappropriate - "identity" is already taken - "identity_element" seems to long - "I" is too ambiguous - "unit" seems ambiguous with physical units Following Laws should hold -------------------------- Left Identity βŠ•(neutral(T), t::T) == t Right Identity βŠ•(t::T, neutral(T)) == t """ function neutral end neutral(T::Type) = neutral # we use the singleton type itself as the generic neutral value neutral(a) = neutral(typeof(a)) """ combine(::T, ::T)::T # overload this βŠ•(::T, ::T)::T # alias \\oplus combine(a, b, c, d, ...) # using combine(a, b) internally Associcative combinator operator. The symbol `βŠ•` (\\oplus) following http://hackage.haskell.org/package/base-unicode-symbols-0.2.3/docs/Data-Monoid-Unicode.html # Following Laws should hold Associativity βŠ•(::T, βŠ•(::T, ::T)) == βŠ•(βŠ•(::T, ::T), ::T) """ function combine end const βŠ• = combine combine(a, b, c, more...) = foldl(βŠ•, more, init=(aβŠ•b)βŠ•c) # supporting `neutral` as generic neutral value combine(::typeof(neutral), b) = b combine(a, ::typeof(neutral)) = a combine(::typeof(neutral), ::typeof(neutral)) = neutral for reduce ∈ [:reduce, :foldl, :foldr] reduce_monoid = Symbol(reduce, "_monoid") _reduce_monoid = Symbol("_", reduce_monoid) @eval begin """ $($reduce_monoid)(itr; init=TypeClasses.neutral) Combines all elements of `itr` using the initial element `init` if given and `TypeClasses.combine`. """ function $reduce_monoid(itr; init=neutral) # taken from Base._foldl_impl # Unroll the while loop once to hopefully infer the element type at compile time y = iterate_named(itr) isnothing(y) && return init v = combine(init, y.value) while true y = iterate_named(itr, y.state) isnothing(y) && break v = combine(v, y.value) end return v end end end # Alternative # =========== """ orelse(a, b) # overload this ⊘(a, b) # alias \\oslash orelse(a, b, c, d, ...) # using orelse(a, b) internally Implements an alternative logic, like having two options a and b, taking the first valid one. We decided for "orelse" instead of "alternatives" to highlight the intrinsic asymmetry in choosing. The operator ⊘ (\\oslash) is choosen to have an infix operator which is similar to \\oplus, however clearly distinguishable, asymmetric, and somehow capturing a choice semantics. The slash actually is used to indicate choice (at least in some languages, like German), and luckily \\oslash exists (and is not called \\odiv). """ function orelse end const ⊘ = orelse orelse(a, b, c, more...) = foldl(⊘, more, init=(a⊘b)⊘c)
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
4398
using .Dictionaries # Monoid / Alternative # ==================== TypeClasses.neutral(T::Type{<:AbstractDictionary}) = T() # generic combine/βŠ• for Dict: using βŠ• on the elements when needed """ ```jldoctest julia> using TypeClasses, Dictionaries julia> dict1 = Dictionary([:a, :b, :c], ["1", "2", "3"]) 3-element Dictionaries.Dictionary{Symbol, String} :a β”‚ "1" :b β”‚ "2" :c β”‚ "3" julia> dict2 = Dictionary([:b, :c, :d], ["4", "5", "6"]) 3-element Dictionaries.Dictionary{Symbol, String} :b β”‚ "4" :c β”‚ "5" :d β”‚ "6" julia> dict1 βŠ• dict2 4-element Dictionaries.Dictionary{Symbol, String} :a β”‚ "1" :b β”‚ "24" :c β”‚ "35" :d β”‚ "6" ``` """ function TypeClasses.combine(d1::AbstractDictionary, d2::AbstractDictionary) d1_combined = map(pairs(d1)) do (key, value) if key in keys(d2) value βŠ• d2[key] else value end end remaining_keys = setdiff(keys(d2), keys(d1)) merge(d1_combined, getindices(d2, remaining_keys)) end # generic orelse/⊘ for Dict """ orelse(d1::Dict, d2::Dict) -> Dict Following the orelse semantics on Option values, the first value is retained, and the second is dropped. Hence this is the flipped version of `Base.merge`. """ TypeClasses.orelse(d1::AbstractDictionary, d2::AbstractDictionary) = merge(d2, d1) # Functor / Applicative / Monad # ============================= # adapted from the Scala Cats implementation https://github.com/typelevel/cats/blob/main/core/src/main/scala/cats/instances/map.scala # map/foreach are already defined # there is no TypeClasses.pure implementation because we cannot come up with an arbitrary key """ ```jldoctest julia> using TypeClasses, Dictionaries julia> dict1 = Dictionary(["a", "b", "c"], [1, 2, 3]) 3-element Dictionaries.Dictionary{String, Int64} "a" β”‚ 1 "b" β”‚ 2 "c" β”‚ 3 julia> dict2 = Dictionary(["b", "c", "d"], [2, 3, 4]) 3-element Dictionaries.Dictionary{String, Int64} "b" β”‚ 2 "c" β”‚ 3 "d" β”‚ 4 mapn(+, dict1, dict2) 2-element Dictionaries.Dictionary{String, Int64} "b" β”‚ 4 "c" β”‚ 6 ``` """ # TypeClasses.ap(f::AbstractDictionary, d::AbstractDictionary) = TypeClasses.default_ap_having_map_flatmap(f, d) """ ```jldoctest julia> using TypeClasses, Dictionaries julia> dict = Dictionary(["a", "b", "c"], [1, 2, 3]) 3-element Dictionaries.Dictionary{String, Int64} "a" β”‚ 1 "b" β”‚ 2 "c" β”‚ 3 julia> f(x) = Dictionary(["b", "c", "d"], [10x, 20x, 30x]) f (generic function with 1 method) julia> flatmap(f, dict) 2-element Dictionaries.Dictionary{String, Int64} "b" β”‚ 20 "c" β”‚ 60 ``` """ function TypeClasses.flatmap(f, d::AbstractDictionary) returntype = Core.Compiler.return_type(f, Tuple{eltype(d)}) result = similar(d, eltype(returntype)) isused = fill(false, d) for (key, value) in pairs(d) subdict = f(value) # only add the key if key appears in both Dictionaries if key in keys(subdict) result[key] = subdict[key] isused[key] = true end end # finally we may have lost a couple of keys getindices(result, findall(isused)) end # FlipTypes # ========= """ ```jldoctest julia> using TypeClasses, Dictionaries julia> d1 = dictionary([:a => Option(1), :b => Option(2)]) 2-element Dictionaries.Dictionary{Symbol, Identity{Int64}} :a β”‚ Identity(1) :b β”‚ Identity(2) julia> flip_types(d1) Identity({:a = 1, :b = 2}) julia> d2 = dictionary([:a => Option(1), :b => Option()]) 2-element Dictionaries.Dictionary{Symbol, Option{Int64}} :a β”‚ Identity(1) :b β”‚ Const(nothing) julia> flip_types(d2) Const(nothing) ``` """ function TypeClasses.flip_types(a::A) where A <: AbstractDictionary iter = pairs(a) first = iterate(iter) constructdict(key, c) = fill(c, getindices(a, Indices([key]))) # using fill to create the correct type automatically if first === nothing # only in this case we actually need `pure(eltype(A))` and `neutral(A)` # for non-empty sequences everything works for Types without both pure(eltype(A), neutral(Base.typename(A).wrapper)) else (key, b), state = first start = map(c -> constructdict(key, c), b) # we can only combine on ABC Base.foldl(Iterators.rest(iter, state); init = start) do acc, (key, b) mapn(acc, b) do accβ€², c # working in applicative context B accβ€² βŠ• constructdict(key, c) # combining on AC end end end end
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
1464
using TypeClasses """ considerations: because `Base.typename(Vector).wrapper == Array`, we dispatch everything on AbstractArray to support AbstractVector. If later on the AbstractArray should be separated from AbstractVector, someone needs to think about a neat way to circumvent this problem. As of now this seems to be a great solution. """ # MonoidAlternative # ================= TypeClasses.neutral(T::Type{<:AbstractArray}) = convert(T, []) TypeClasses.combine(v1::AbstractArray, v2::AbstractArray) = [v1; v2] # general syntax which is overloaded by concrete AbstractVector types # FunctorApplicativeMonad # ======================= TypeClasses.pure(T::Type{<:AbstractArray}, a) = convert(Base.typename(T).wrapper, [a]) TypeClasses.ap(fs::AbstractArray, v::AbstractArray) = vcat((map(f, v) for f in fs)...) # for flattening we solve type-safety by converting to Vector elementwise # this also gives well-understandable error messages if something goes wrong function TypeClasses.flatmap(f, v::AbstractArray) type = Base.typename(typeof(v)).wrapper vcat((convert(type, f(x)) for x in v)...) end # FlipTypes # ========= # we define flip_types for all Vector despite it only works if the underlying element defines `ap` # as there is no other sensible definition for Iterable, an error that the element does not implement `ap` # is actually the correct error flip_types(v::AbstractArray) = default_flip_types_having_pure_combine_apEltype(v)
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
1560
using TypeClasses # Monoid instances # ================ # this is standard Applicative combine implementation # there is no other sensible definition for combine and hence if this does fail, it fails correctly TypeClasses.combine(a::Callable, b::Callable) = mapn(combine, a, b) # we do not implement the same for `orelse`, as `orelse` is usually defined on the container level, but there is no sensible default implementation. # it is not possible to implement neutral, as we do not know the element type without executing the function # Monad instances # =============== # there is no definition for Base.foreach, as a callable is not runnable without knowing the arguments TypeClasses.map(f, g::Callable) = Callable((args...; kwargs...) -> f(g(args...; kwargs...))) TypeClasses.pure(::Type{<:Callable}, a) = (args...; kwargs...) -> a TypeClasses.ap(f::Callable, g::Callable) = Callable((args...; kwargs...) -> f(args...; kwargs...)(g(args...; kwargs...))) # we cannot overload this generically, because `Base.map(f, ::Vector...)` would get overwritten as well (even without warning surprisingly) TypeClasses.map(f, a::Callable, b::Callable, more::Callable...) = mapn(f, a, b, more...) # we don't use convert, but directly use function call, # which should give readable errors that a something is not callable, and is a bit more flexible TypeClasses.flatmap(f, g::Callable) = Callable((args...; kwargs...) -> f(g(args...; kwargs...))(args...; kwargs...)) # FlipTypes instance # ================== # there cannot be any flip_types for functions
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
1981
using TypeClasses """ IMPORTANT: we do NOT support AbstractDict, because there is no general way to map over such a type, i.e. we cannot easily construct new AbstractDict from the same type, but with small alterations. """ # Monoid Instances for standard Dict # =================================== # generic neutral for Dict TypeClasses.neutral(::Type{Dict}) = Dict() TypeClasses.neutral(::Type{Dict{K, V}}) where {K, V} = Dict{K, V}() # generic combine/βŠ• for Dict: using βŠ• on the elements when needed function TypeClasses.combine(d1::Dict, d2::Dict) newdict = Dict( key => haskey(d2, key) ? value βŠ• d2[key] : value for (key, value) in d1) for (key, value) in d2 if !haskey(newdict, key) push!(newdict, key => value) end end newdict end # generic orelse/⊘ for Dict """ orelse(d1::Dict, d2::Dict) -> Dict Following the orelse semantics on Option values, the first value is retained, and the second is dropped. Hence this is the flipped version of `Base.merge`. """ TypeClasses.orelse(d1::Dict, d2::Dict) = merge(d2, d1) # Functor/Applicative/Monad # ========================= # Dict does not support map, as it would restrict the function applied to return Pairs and not arbitrary types # TypeClasses.map(f, d::Dict) = Dict(f(pair) for pair in d) # FlipTypes # ========= function TypeClasses.flip_types(a::Dict) iter = a first = iterate(iter) if first === nothing # only in this case we actually need `pure(eltype(A))` and `neutral(A)` # for non-empty sequences everything works for Types without both pure(eltype(a), neutral(Dict)) else (key, b), state = first start = map(c -> Dict(key => c), b) # we can only combine on ABC Base.foldl(Iterators.rest(iter, state); init = start) do acc, (key, b) mapn(acc, b) do accβ€², c # working in applicative context B accβ€² βŠ• Dict(key => c) # combining on AC end end end end
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
2597
import Distributed: Future, @spawnat, RemoteChannel, RemoteException # Monoid instances # ================ # this is standard Applicative combine implementation # there is no other sensible definition for combine and hence if this does fail, it fails correctly TypeClasses.combine(a::Future, b::Future) = mapn(combine, a, b) """ orelse(future1, future2, ...) future1 ⊘ future2 Runs both in parallel and collects which ever result is first. Then interrupts all other futures and returns the found result. """ TypeClasses.orelse(a::Future, b::Future, more::Future...) = @spawnat :any begin n = length(more) + 2 c = Channel(n) # all tasks should in principle be able to send there result without waiting futures = (a, b, more...) futuresβ€² = map(futures) do future @spawnat :any begin # fetch returns an RemoteException in case something failed, it does not throw an error put!(c, fetch(future)) end end exceptions = Vector{Exception}(undef, n) for i in 1:n result = take!(c) if isa(result, RemoteException) # all exceptions are Thrown{TaskFailedException} exceptions[i] = if isa(result.captured.ex, MultipleExceptions) # extract MultipleExceptions for better readability result.captured.ex else result end # we found an error, hence need to wait for another result continue end # no error, i.e. we found the one result we wanted to find close(c) # we only need one result for t in (futuresβ€²..., futures...) # all tasks can be interrupted now that we have the first result @spawnat :any Base.throwto(t, InterruptException()) end return result # break for loop end # only if all n tasks failed return throw(MultipleExceptions(exceptions...)) end # FunctorApplicativeMonad # ======================= function TypeClasses.foreach(f, x::Future) f(fetch(x)) nothing end TypeClasses.map(f, x::Future) = @spawnat :any f(fetch(x)) TypeClasses.pure(::Type{<:Future}, x) = @spawnat :any x # we use the default implementation of ap which follows from flatten # TypeClasses.ap TypeClasses.ap(f::Future, x::Future) = @spawnat :any fetch(f)(fetch(x)) # we don't use convert for typesafety, as fetch is more flexible and also enables typechecks # e.g. this works seamlessly to combine a Task into a Future TypeClasses.flatmap(f, x::Future) = @spawnat :any fetch(f(fetch(x))) # FlipTypes # ========= # does not make much sense as this would need to execute the Future, and map over its returned value, # creating a bunch dummy Futures within.
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
2130
using TypeClasses """ Iterables can be seen two ways. On the one hand, an iterable is mainly defined by its `iterate` method, which can be thought of as a kind of TypeClass (similar to how `map`, `combine`, `Monad`, or `Monoid` refer to TypeClasses). In this sense being iterable is regarded as a decisive characteristic which is usually checked via `Base.isiterable`. As an example, the TypeClass FlipTypes has a default implementation which uses exactly this. The alternativ semantics, which is implemented in this file, is that an iterable type can be seen as an (abstract) DataType on top of which we can define TypeClasses themselves. Because of this duality, we don't define TypeClasses for iterables directly by dispatching on `isiterable`, but we provide a custom wrapper `TypeClasses.Iterable` on which all TypeClasses are defined. I.e. if you want to use standard TypeClasses on top of your iterable Type, just wrap it within an `Iterable`: ``` myiterable = ... Iterable(myiterable) ``` """ # MonoidAlternative # ================= TypeClasses.neutral(iter::Type{<:Iterable}) = Iterable() TypeClasses.combine(it1::Iterable, it2::Iterable) = Iterable(chain(it1.iter, it2.iter)) # FunctorApplicativeMonad # ======================= TypeClasses.pure(::Type{<:Iterable}, a) = Iterable(TypeClasses.DataTypes.Iterables.IterateSingleton(a)) TypeClasses.ap(fs::Iterable, it::Iterable) = Iterable(f(a) for f ∈ fs.iter for a ∈ it.iter) # Base.map(f, iter1, iter2, iter3...) is already defined and uses zip semantics, hence we don't overload it # Flattening Iterables works with everything being iterable itself (it is treated as iterable) TypeClasses.flatten(it::Iterable) = Iterable(Iterators.flatten(it.iter)) TypeClasses.flatmap(f, it::Iterable) = flatten(map(f, it)) # FlipTypes # ========= # we define flip_types for all iterable despite it only works if the underlying element defines `ap` # as there is no other sensible definition for Iterable, an error that the element does not implement `ap` # is actually the correct error flip_types(iter::Iterable) = default_flip_types_having_pure_combine_apEltype(iter)
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
137
# extra Monoid instances # Note, we do not implement neutral for functions like + or *, as this is already handled by Base.reduce_empty
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
517
using TypeClasses # we assume that Pair(a::A, b::B) always constructs the most specific Pair type Pair{A, B} # TODO is this really the case? It could be, but is it true? # MonoidAlternative # ================= TypeClasses.neutral(::Type{Pair{F, S}}) where {F, S} = neutral(F) => neutral(S) TypeClasses.combine(p1::Pair, p2::Pair) = combine(p1.first, p2.first) => combine(p1.second, p2.second) # we don't implement orelse, as it is commonly meant on container level, but there is no obvious failure semantics here
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
1380
using TypeClasses # Monoid instances # ================ # this is standard Applicative combine implementation # there is no other sensible definition for combine and hence if this does fail, it fails correctly TypeClasses.combine(a::State, b::State) = mapn(combine, a, b) # we don't do the same for orelse, as orelse lives on the container level, but there is no default definition of orelse for State # FunctorApplicativeMonad # ======================= # there is no implementation of foreach for State, as we cannot look into the state function TypeClasses.map(f, a::State) = State() do state value, newstate = a(state) f(value), newstate end TypeClasses.pure(::Type{<:State}, a) = State() do state a, state end TypeClasses.ap(f::State, a::State) = State() do state0 func, state1 = f(state0) value, state2 = a(state1) func(value), state2 end # we cannot overload this generically, because `Base.map(f, ::Vector...)` would get overwritten as well (even without warning surprisingly) TypeClasses.map(f, a::State, b::State, more::State...) = mapn(f, a, b, more...) TypeClasses.flatmap(f, a::State) = State() do state0 value, state1 = a(state0) convert(State, f(value))(state1) end # FlipTypes # ========= # flip_types does not makes sense for State, as we cannot evalute the State without running the statefunctions on top # of a given initial state
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
133
using TypeClasses # Monoid # ====== TypeClasses.neutral(::Type{String}) = "" TypeClasses.combine(s1::String, s2::String) = s1 * s2
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
2503
# Monoid instances # ================ # this is standard Applicative combine implementation # there is no other sensible definition for combine and hence if this does fail, it fails correctly TypeClasses.combine(a::Task, b::Task) = mapn(combine, a, b) """ orelse(task1, task2, ...) task1 ⊘ task2 Runs both in parallel and collects which ever result is first. Then interrupts all other tasks and returns the found result. """ TypeClasses.orelse(a::Task, b::Task, more::Task...) = @async begin n = length(more) + 2 c = Channel(n) # all tasks should in principle be able to send there result without waiting tasks = (a, b, more...) tasksβ€² = map(tasks) do task @async begin tried = @TryCatch TaskFailedException fetch(task) # we need to capture errors too, so that in case everything errors out, this is still ending put!(c, tried[]) end end exceptions = Vector{Exception}(undef, n) for i in 1:n result = take!(c) if isa(result, Thrown) # all exceptions are Thrown{TaskFailedException} exceptions[i] = if isa(result.exception.task.exception, MultipleExceptions) # extract MultipleExceptions for better readability result.exception.task.exception else result end # we found an error, hence need to wait for another result continue end # no error, i.e. we found the one result we wanted to find close(c) # we only need one result for t in (tasksβ€²..., tasks...) # all tasks can be interrupted now that we have the first result @async Base.throwto(t, InterruptException()) end return result # break for loop end # only if all n tasks failed return throw(MultipleExceptions(exceptions...)) end # FunctorApplicativeMonad # ======================= function TypeClasses.foreach(f, x::Task) f(fetch(x)) nothing end TypeClasses.map(f, x::Task) = @async f(fetch(x)) TypeClasses.pure(::Type{<:Task}, x) = @async x # we use the default implementation of ap which follows from flatten # TypeClasses.ap TypeClasses.ap(f::Task, x::Task) = @async fetch(f)(fetch(x)) # we don't use convert for typesafety, as fetch is more flexible and also enables typechecks # e.g. this works seamlessly to combine a Future into a Task TypeClasses.flatmap(f, x::Task) = @async fetch(f(fetch(x))) # FlipTypes # ========= # does not make much sense as this would need to execute the Task, and map over its returned value, # creating a bunch dummy Tasks within.
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
1285
using TypeClasses # MonoidAlternative # ================= function create_tuple_monoid_definitions(n) # unary and type arguments for `neutral` unary_typevars = Symbol.(:A, 1:n) unary_args = [:(a::Type{Tuple{$(unary_typevars...)}})] unary_return(unary) = :(tuple($(unary.(unary_typevars)...))) # binary and value arguments, for both `combine` and `orelse` binary_typevars_1 = Symbol.(:A, 1:n) binary_typevars_2 = Symbol.(:B, 1:n) binary_args = [:(a::Tuple{$(binary_typevars_1...)}), :(b::Tuple{$(binary_typevars_2...)})] binary_return(binary) = :(tuple($(binary.([:(getfield(a, $i)) for i in 1:n], [:(getfield(b, $i)) for i in 1:n])...))) quote function TypeClasses.neutral($(unary_args...)) where {$(unary_typevars...)} $(unary_return(A -> :(neutral($A)))) end function TypeClasses.combine($(binary_args...)) where {$(binary_typevars_1...), $(binary_typevars_2...)} $(binary_return((a, b) -> :($a βŠ• $b))) end # we don't implement orelse, as it is commonly meant on container level, but there is no obvious failure semantics here end end macro create_tuple_monoid_definitions(n::Int) esc(Expr(:block, [create_tuple_monoid_definitions(i) for i ∈ 1:n]...)) end @create_tuple_monoid_definitions 20 # 20 is an arbitrary number
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
1935
using TypeClasses # MonoidAlternative # ================= TypeClasses.neutral(::Type{Writer{Accumulator, Value}}) where {Accumulator, Value} = neutral(Accumulator) => neutral(Value) TypeClasses.combine(w1::Writer, w2::Writer) = Writer(combine(w1.acc, w2.acc), combine(w1.value, w2.value)) # we don't implement orelse, as it is commonly meant on container level, but there is no obvious failure semantics here # FunctorApplicativeMonad # ======================= TypeClasses.foreach(f, p::Writer) = f(p.value); nothing TypeClasses.map(f, p::Writer) = Writer(p.acc, f(p.value)) # pure needs Neutral on First function TypeClasses.pure(::Type{<:Writer{Acc}}, a) where {Acc} Writer(neutral(Acc), a) end # We fall back to assume that the general writer uses Option values in order to have a neutral value # this should be okay, as it is canonical extension for any Semigroup to an Monoid function TypeClasses.pure(::Type{<:Writer}, a) Writer(neutral, a) end # Writer always defines `combine` on `acc` function TypeClasses.ap(f::Writer, a::Writer) Writer(combine(f.acc, a.acc), f.value(a.value)) end # we cannot overload this generically, because `Base.map(f, ::Vector...)` would get overwritten as well (even without warning surprisingly) TypeClasses.map(f, a::Writer, b::Writer, more::Writer...) = mapn(f, a, b, more...) function TypeClasses.flatmap(f, a::Writer) # we intentionally only convert the container to Writer, and leave the responsibility for the accumulator to the `combine` function # (one reason is that all monads are only converted on the container side, another is that it seems quite difficult to convert MyType{Option} correctly, because it is a Union type.) nested_writer = convert(Writer, f(a.value)) Writer(combine(a.acc, nested_writer.acc), nested_writer.value) end # flip_types # ========== function TypeClasses.flip_types(a::Writer) TypeClasses.map(x -> Writer(a.acc, x), a.value) end
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
812
# MonoidAlternative # ================= # for convenience we forward Monoid definitions from the wrapped type TypeClasses.neutral(::Type{Const{T}}) where {T} = Const(TypeClasses.neutral(T)) TypeClasses.combine(a::Const, b::Const) = Const(a.value βŠ• b.value) # we support the special value Const(nothing) by defining Monoid on Nothing TypeClasses.neutral(::Type{Nothing}) = nothing TypeClasses.combine(::Nothing, ::Nothing) = nothing # Const denotes failure, possibly trying again, hence we take the second attempt. TypeClasses.orelse(a::Const, b::Const) = b # FunctorApplicativeMonad # ======================= TypeClasses.ap(f::Const, a::Const) = f # short cycling behaviour TypeClasses.flatmap(f, a::Const) = a # FlipTypes # ========= TypeClasses.flip_types(a::Const) = TypeClasses.map(Const, a.value)
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
717
# FunctorApplicativeMonad # ======================= TypeClasses.pure(::Type{<:ContextManager}, x) = @ContextManager cont -> cont(x) TypeClasses.flatmap(f, x::ContextManager) = flatten(map(f, x)) TypeClasses.flatten(c::ContextManager) = Iterators.flatten(c) # we cannot overload this generically, because `Base.map(f, ::Vector...)` would get overwritten as well (even without warning surprisingly) # hence we do it individually for ContextManager Base.map(f, a::ContextManager, b::ContextManager, more::ContextManager...) = mapn(f, a, b, more...) # FlipTypes # ========= # does not make much sense as if I would flip_types ContextManager, I need to evaluate the context # hence I could directly flatten instead
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
2750
# We define the Either type simply by the interactions between Identity and Const # MonoidAlternative # ================= # Every Const is neutral towards Identity, we choose Const(nothing) here, the default one, following the Option implementation. TypeClasses.neutral(::Type{<:Identity}) = Option() # Option()::Const{Nothing}, so this should help for the Option case TypeClasses.neutral(::Type{Const{Nothing}}) = Option() # orelse and combine behave identical for Either, both return the Identity element # - for combine semantics we follow the general approach of """Any semigroup S may be turned into a monoid simply by adjoining an element e not in S and defining e β€’ s = s = s β€’ e for all s ∈ S""" https://en.wikipedia.org/wiki/Monoid) TypeClasses.combine(a::Identity, b::Const) = a TypeClasses.combine(a::Const, b::Identity) = b # - for orelse semantic Identity denotes success TypeClasses.orelse(a::Identity, b::Const) = a TypeClasses.orelse(a::Const, b::Identity) = b # for generic Either, both Const and Identity can be combined on their own, but combining Const with Identity gives Identity. # Hence, to comply with monoid laws, the neutral element is `Cons(neutral(L))` TypeClasses.neutral(::Type{Either{L, R}}) where {L, R} = Const(neutral(L)) TypeClasses.neutral(::Type{Either{L, <:UR}}) where {L, UR} = Const(neutral(L)) # we don't provide the fallback of Option if given a generic Either type, as the monoid laws would get broken # TypeClasses.neutral(::Type{Either}) = Const(nothing) TypeClasses.neutral(::Type{Option{T}}) where T = Const(nothing) TypeClasses.neutral(::Type{Option{<:UT}}) where UT = Const(nothing) TypeClasses.neutral(::Type{Option}) = Const(nothing) # FunctorApplicativeMonad # ======================= TypeClasses.ap(f::Const, x::Identity) = f TypeClasses.ap(f::Identity, x::Const) = x # you can think of Identity as the neutral element for monadic composition: adding Identity as an additional layer, and then flattening the layers, nothing is changed in total. TypeClasses.pure(::Type{Either{L, R}}, a) where {L, R} = Identity(a) # includes Option, as Const{Nothing} => L=Nothing TypeClasses.pure(::Type{Either{L, <:UR}}, a) where {L, UR} = Identity(a) TypeClasses.pure(::Type{Either{<:UL, R}}, a) where {UL, R} = Identity(a) # includes Try as Const{<:Exception} => UL = Exception TypeClasses.pure(::Type{Either{<:UL, <:UR}}, a) where {UL, UR} = Identity(a) # includes Either # we cannot overload this generically, because `Base.map(f, ::Vector...)` would get overwritten as well (even without warning surprisingly) # hence we do it individually for Either Base.map(f, a::Either, b::Either, more::Either...) = mapn(f, a, b, more...) # FlipTypes # ========= # all covered by Identity and Const
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
910
# MonoidAlternative # ================= # we don't define a Identity-only TypeClasses.neutral # this could interfere with the more generic neutral definition within `Either` (every Const is neutral towards Identity) # for convenience we forward Monoid definitions from the wrapped type TypeClasses.combine(a::Identity, b::Identity) = Identity(a.value βŠ• b.value) # Identity denotes success, and first success wins TypeClasses.orelse(a::Identity, b::Identity) = a # FunctorApplicativeMonad # ======================= TypeClasses.pure(::Type{<:Identity}, a) = Identity(a) TypeClasses.ap(f::Identity, a::Identity) = Identity(f.value(a.value)) # for convenience, Identity does not use convert, whatever monad is returned is valid, providing maximum flexibility. TypeClasses.flatmap(f, a::Identity) = f(a.value) # FlipTypes # ========= TypeClasses.flip_types(a::Identity) = TypeClasses.map(Identity, a.value)
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
197
using DataTypesBasic # Monoid support for Exceptions TypeClasses.neutral(::Type{<:Exception}) = MultipleExceptions() TypeClasses.combine(e1::Exception, e2::Exception) = MultipleExceptions(e1, e2)
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
1362
module Utils export chain, isiterable, @ifsomething, iterate_named # include("unionall_implementationdetails.jl") # TODO do we need this? chain(itr...) = Iterators.flatten(itr) isiterable(value) = isiterable(typeof(value)) isiterable(type::Type) = Base.isiterable(type) """ @ifsomething expr If `expr` evaluates to `nothing`, equivalent to `return nothing`, otherwise the macro evaluates to the value of `expr`. Not exported, useful for implementing iterators. ```jldoctest julia> using TypeClasses.Utils julia> @ifsomething iterate(1:2) (1, 1) julia> let elt, state = @ifsomething iterate(1:2, 2); println("not reached"); end ``` """ macro ifsomething(ex) quote result = $(esc(ex)) result === nothing && return nothing result end end """ result = iterate_named(iterable) result = iterate_named(iterable, state) Exactly like `iterate`, with the addition that you can use `result.value` in addition to 'result[1]' and `result.state` for `result[2]`. It will return a named tuple respectively if not nothing, hence also the name. Can be used instead of `iterate`. ```jldoctest julia> using TypeClasses.Utils julia> iterate_named(["one", "two"]) (value = "one", state = 2) ``` """ function iterate_named(iter, state...) value, stateβ€² = @ifsomething iterate(iter, state...) (value=value, state=stateβ€²) end end # module
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
3510
# Check the interactions of different Containers via `convert` using TypeClasses using Test using Suppressor using DataTypesBasic splitln(str) = split(strip(str), "\n") load_square(x, prefix="") = @ContextManager function (cont) println("$(prefix)before $x") result = cont(x*x) println("$(prefix)after $x") result end # Multiple Combinations # ===================== # unfortunately this does not work, as the typeinference does not work # and hence an Array of Any is constructed instead of an Array of ContextManager # the version without the Array component works like a charm h2() = @syntax_flatmap begin (a, b) = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)] c = iftrue(a % 2 == 0) do a + b end d = load_square(c) # c*c @pure d end @test @suppress(h2()) == [25, 81] @test splitln(@capture_out h2()) == ["before 5", "after 5", "before 9", "after 9"] # Try # --- mytry(x) = x == 4 ? error("error") : x h3() = @syntax_flatmap begin (a, b) = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)] c = iftrue(a % 2 == 0) do a + b end d = load_square(c) # c*c e = @Try mytry(d / a) @pure e + 1 end @test @suppress(h3()) == [(2+3)^2/2 + 1, (4+5)^2/4 + 1] # TODO not working because of bad type-inference @test splitln(@capture_out h3()) == [ "before 5", "after 5", "before 9", "after 9", ] # Either # ------ h4() = @syntax_flatmap begin (a, b) = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)] c = iftrue(a % 2 == 0) do a + b end d = load_square(c) # c*c f = either("left", d > 4, :right) e = @Try "$a, $b, $c, $d, $f" end @test @suppress(h4()) == ["2, 3, 5, 25, right", "4, 5, 9, 81, right"] @test splitln(@capture_out h4()) == [ "before 5", "after 5", "before 9", "after 9", ] # Writer + ContextManager # --------------------- writer_cm() = @syntax_flatmap begin i = Writer("hi", 4) l = load_square(i) Writer(" $l yes", l+i) end # importantly, writer does not work smoothly with other Contexts, but only by forgetting its accumulator @test @suppress(writer_cm()) != Writer("hi 4 yes", 4*4+4) @test @suppress(writer_cm()) == Writer("hi", 4*4+4) @test splitln(@capture_out writer_cm()) == [ "before 4", "after 4" ] # combining ContextManager with other monads # ------------------------------------------ # ContextManager as main Monad cm2 = @syntax_flatmap begin i = load_square(4) v = [i, i+1, i+3] @pure v + 2 end @test_throws MethodError @suppress(cm2(x -> x).value) == [6,7,9] @test_throws MethodError splitln(@capture_out cm2(x -> x)) == ["before 4", "after 4"] # ContextManager as sub monad vector2() = @syntax_flatmap begin i = [1,2,3] c = load_square(i) @pure c + 2 end @test @suppress(vector2()) == [1*1+2, 2*2+2, 3*3+2] @test splitln(@capture_out vector2()) == [ "before 1", "after 1", "before 2", "after 2", "before 3", "after 3"] # alternating contextmanager and vector does not work, as there is no way to convert a vector to a contextmanager multiplecm() = @syntax_flatmap begin i = [1,2,3] c = load_square(i, "i ") j = [c, c*c] c2 = load_square(j, "j ") @pure c + c2 end @test_throws MethodError @suppress(multiplecm()) == [2, 2, 4, 6, 6, 12] @test_throws MethodError splitln(@capture_out multiplecm()) == ["i before 1", "j before 1", "j after 1", "j before 1", "j after 1", "i after 1", "i before 2", "j before 2", "j after 2", "j before 4", "j after 4", "i after 2", "i before 3", "j before 3", "j after 3", "j before 9", "j after 9", "i after 3"]
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
2104
using Test using TypeClasses using DataTypesBasic using Suppressor using Documenter # Test Utils splitln(str) = split(strip(str), "\n") if v"1.6" <= VERSION < v"1.7" # somehow only Julia 1.6 does this correctly @test isempty(detect_ambiguities(TypeClasses)) # doctests are super instable, hence we only do it for a specific Julia Version doctest(TypeClasses) end @testset "TypeClasses" begin @testset "MonoidAlternative" begin include("TypeClasses/MonoidAlternative.jl") end @testset "FunctorApplicativeMonad" begin include("TypeClasses/FunctorApplicativeMonad.jl") end @testset "FlipTypes" begin include("TypeClasses/FlipTypes.jl") end end @testset "TypeInstances" begin @testset "AbstractDictionary" begin include("TypeInstances/AbstractDictionary.jl") end @testset "AbstractVector" begin include("TypeInstances/AbstractVector.jl") end @testset "Callable" begin include("TypeInstances/Callable.jl") end @testset "Dict" begin include("TypeInstances/Dict.jl") end @testset "Future" begin include("TypeInstances/Future.jl") end @testset "Iterable" begin include("TypeInstances/Iterable.jl") end @testset "Pair" begin include("TypeInstances/Pair.jl") end @testset "State" begin include("TypeInstances/State.jl") end @testset "Task" begin include("TypeInstances/Task.jl") end @testset "Tuple" begin include("TypeInstances/Tuple.jl") end @testset "Writer" begin include("TypeInstances/Writer.jl") end end @testset "TypeInstances_DataTypesBasic" begin @testset "Const" begin include("TypeInstances_DataTypesBasic/Const.jl") end @testset "Identity" begin include("TypeInstances_DataTypesBasic/Identity.jl") end @testset "Either" begin include("TypeInstances_DataTypesBasic/Either.jl") end @testset "Option" begin include("TypeInstances_DataTypesBasic/Option.jl") end @testset "Try" begin include("TypeInstances_DataTypesBasic/Try.jl") end @testset "ContextManager" begin include("TypeInstances_DataTypesBasic/ContextManager.jl") end end
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
105
using Test left = flip_types([ Option(1), Option(:b)]) right = Option([1, :b]) @test left == right
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
807
@test eltype(Vector{Int}) == Int # we use plain Identity Monads for testing # Applicative defaults # -------------------- struct TestApDefault x end TypeClasses.map(f, x::TestApDefault) = TypeClasses.default_map_having_ap_pure(f, x) TypeClasses.pure(::Type{TestApDefault}, x) = TestApDefault(x) TypeClasses.ap(f::TestApDefault, x::TestApDefault) = TestApDefault(f.x(x.x)) @test map(TestApDefault(4)) do x x*x end == TestApDefault(4*4) # Monad defaults # -------------- struct TestDefaultFFlattenFunctor x end TypeClasses.map(f, x::TestDefaultFFlattenFunctor) = TestDefaultFFlattenFunctor(f(x.x)) TypeClasses.flatmap(f, x::TestDefaultFFlattenFunctor) = f(x.x) @test mapn(TestDefaultFFlattenFunctor(3), TestDefaultFFlattenFunctor(4)) do x, y x + y end == TestDefaultFFlattenFunctor(3 + 4)
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
612
# Define and test Monoid instance for Int # --------------------------------------- TypeClasses.combine(a::Int, b::Int) = a + b @test reduce_monoid([1,2,3,1]) == 7 @test foldl_monoid([1,2,3,4]) == 10 @test foldr_monoid([1,2,3,100], init=3000) == 3106 # Test default Semigroup instance for String # ------------------------------------------ @test reduce_monoid(["hi"," ","du"], init="!") == "!hi du" # Test `neutral` singleton value # ------------------------------ @test combine(neutral, :anything) == :anything @test combine("anything", neutral) == "anything" @test combine(neutral, neutral) == neutral
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
1602
using Test using TypeClasses using Dictionaries # MonoidAlternative # ================= @test neutral(Dictionary) == Dictionary() @test neutral(Dictionary{String, Int}) == Dictionary{String, Int}() # we can combine any Dict where elements can be combined d1 = dictionary([:a => "3", :b => "1"]) d2 = dictionary([:a => "5", :b => "9", :c => "15"]) @test d1 βŠ• d2 == dictionary([:a => "35", :b => "19", :c => "15"]) @test d1 ⊘ d2 == dictionary([:a => "3", :b => "1", :c => "15"]) dict1 = Dictionary([:a, :b, :c], ["1", "2", "3"]) dict2 = Dictionary([:b, :c, :d], ["4", "5", "6"]) @test dict1 βŠ• dict2 == Dictionary([:a, :b, :c, :d], ["1", "24", "35", "6"]) dict1 = Dictionary(["a", "b", "c"], [1, 2, 3]) dict2 = Dictionary(["b", "c", "d"], [2, 3, 4]) @test mapn(+, dict1, dict2) == Dictionary(["b", "c"], [4, 6]) dict = Dictionary(["a", "b", "c"], [1, 2, 3]) create_dictionary(x) = Dictionary(["b", "c", "d"], [10x, 20x, 30x]) @test flatmap(create_dictionary, dict) == Dictionary(["b", "c"], [20, 60]) d1 = dictionary([:a => Option(1), :b => Option(2)]) @test flip_types(d1) == Identity(Dictionary([:a, :b], [1, 2])) d2 = dictionary([:a => Option(1), :b => Option()]) @test flip_types(d2) == Const(nothing) @test flip_types(dictionary((:a => [1,2], :b => [3, 4]))) == [ dictionary([:a => 1, :b => 3]), dictionary([:a => 1, :b => 4]), dictionary([:a => 2, :b => 3]), dictionary([:a => 2, :b => 4]), ] @test flip_types([ dictionary((:a => 1, :b => 2)), dictionary((:a => 10, :b => 20)), dictionary((:b => 200, :c => 300)) ]) == dictionary([:b => [2, 20, 200]])
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
1051
# MonoidAlternative # ================= a = [1,2,3] b = [4,5,6] @test a βŠ• b == [a; b] # FunctorApplicativeMonad # ======================= @test eltype(Vector{Int}) == Int @test map(x -> x*x, a) == [1, 4, 9] product_ab = [5, 6, 7, 6, 7, 8, 7, 8, 9] @test mapn(a, b) do x, y x + y end == product_ab h = @syntax_flatmap begin x = a y = b @pure x + y end @test h == product_ab @test pure(Vector{Int}, 3) == [3] # flatten combinations with other Monads # -------------------------------------- @test flatten([Identity(3), Identity(4)]) == [3, 4] @test flatten([Option(3), Option(nothing), Option(4)]) == [3, 4] @test flatten([Try(4), (@Try error("hi")), Try(5)]) == [4, 5] @test flatten([Either{String}(4), either("left", false, 3), Either{Int, String}("right")]) == [4, "right"] h1 = @syntax_flatmap begin a, b = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)] iftrue(a % 2 == 0) do a + b end end @test h1 == [5, 9] # FlipTypes # ======== v = [Option(:a), Option(:b), Option(:c)] @test flip_types(v) == Option([:a, :b, :c])
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
714
using TypeClasses using Test using DataTypesBasic using Suppressor splitln(str) = split(strip(str), "\n") # Combine # ======= a = Callable(x -> "hello $x") b = Callable(x -> "!") (a βŠ• b)(:Albert) # FunctorApplicativeMonad # ======================= g = Callable(x -> x*2) f = Callable(x -> x*x) # just function composition fg = map(g) do x2 f(x2) end @test fg(3) == f(g(3)) fPLUSg = mapn(f, g) do x1, x2 x1 + x2 end @test fPLUSg(3) == f(3) + g(3) fPRODg = @syntax_flatmap begin x1 = f x2 = g @pure x1 * x2 end @test fPRODg(3) == f(3) * g(3) # FlipTypes # ========= # this works because Callable implements `ap` a = Callable.([x -> x, y -> 2y, z -> z*z]) @test flip_types(a)(3) == [3, 6, 9]
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
839
using Test using TypeClasses # MonoidAlternative # ================= @test neutral(Dict) == Dict() @test neutral(Dict{String, Int}) == Dict{String, Int}() # we can combine any Dict where elements can be combined d1 = Dict(:a => "3", :b => "1") d2 = Dict(:a => "5", :b => "9", :c => "15") @test d1 βŠ• d2 == Dict(:a => "35", :b => "19", :c => "15") @test d1 ⊘ d2 == Dict(:a => "3", :b => "1", :c => "15") # FlipTypes # ========= @test flip_types(Dict(:a => [1,2], :b => [3, 4])) == [ Dict(:a => 1, :b => 3), Dict(:a => 1, :b => 4), Dict(:a => 2, :b => 3), Dict(:a => 2, :b => 4), ] # the other way arround does not work, as Dict does not implement Functor/Applicative/Monad interfaces # this is not a MethodError, but a special exception thrown intentionally by Base @test_throws ErrorException flip_types([d1, d2])
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
1342
using TypeClasses using Test using Distributed wait_a_little(f::Function, seconds=0.3) = @spawnat :any begin sleep(seconds) f() end wait_a_little(x, seconds=0.3) = wait_a_little(() -> x, seconds) # Functor, Applicative, Monad # =========================== squared = map(wait_a_little(4)) do x x*x end; # returns a Task @test fetch(squared) == 16 @test typeof(mapn(+, wait_a_little(11), wait_a_little(12))) === Future @test fetch(mapn(+, wait_a_little(11), wait_a_little(12))) == 23 monadic = @syntax_flatmap begin a = wait_a_little(5) b = wait_a_little(a + 3) @pure a, b end; # returns a Task @test fetch(monadic) == (5, 8) @test fetch(pure(Future, "a")) == "a" # Monoid, Alternative # =================== @test fetch(wait_a_little("hello.") βŠ• wait_a_little("world.")) == "hello.world." @test fetch(wait_a_little(:a, 1.0) ⊘ wait_a_little(:b, 2.0)) == :a @test fetch(wait_a_little(:a, 3.0) ⊘ wait_a_little(:b, 2.0)) == :b @test fetch(wait_a_little(() -> error("fails"), 0.1) ⊘ wait_a_little(:succeeds, 0.3)) == :succeeds @test fetch(wait_a_little(:succeeds, 0.3) ⊘ wait_a_little(() -> error("fails"), 0.1)) == :succeeds @test isa(fetch(wait_a_little(() -> error("fails1")) ⊘ wait_a_little(() -> error("fails2")) ⊘ wait_a_little(() -> error("fails3")) ⊘ wait_a_little(() -> error("fails4"))), RemoteException)
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
964
a = Iterable(i for i ∈ [1,2,3]) b = Iterable([4,5,6]) # MonoidAlternative # ================= @test collect(a βŠ• b) == [collect(a); collect(b)] # FunctorApplicativeMonad # ======================= @test map(x -> x*x, a) |> collect == [1, 4, 9] product_ab = [5, 6, 7, 6, 7, 8, 7, 8, 9] @test mapn(a, b) do x, y x + y end |> collect == product_ab h = @syntax_flatmap begin x = a y = b @pure x + y end @test h |> collect == product_ab # Everything Iterable works with Iterable h2 = @syntax_flatmap begin x = a y = isodd(x) ? Option(x*x) : Option() @pure x + y end @test collect(h2) == [2, 12] # However note that the following does not work h3() = @syntax_flatmap begin x = a y = isodd(x) ? Option(x*x) : Option() z = b @pure x, y, z end @test collect(h3()) == [ (x, x*x, z) for x in a for z in b if isodd(x) ] # FlipTypes # ========= it = Iterable(Option(i) for i ∈ [1, 4, 7]) @test map(collect, flip_types(it)) == Option([1, 4, 7])
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
111
# MonoidAlternative # ================= a = "a" => [1] b = "b" => [2,3,4] @test a βŠ• b == ("ab" => [1,2,3,4])
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
1033
using Test using TypeClasses using DataTypesBasic using Suppressor splitln(str) = split(strip(str), "\n") # Combine # ======= a = State(s -> ("hello $s", s+1)) b = State(s -> ("!", s+10)) @test (a βŠ• b)(4) == ("hello 4!", 15) # FunctorApplicativeMonad # ======================= g = State(s -> (s*2, s+1)) f = State(s -> (s*s, s)) # just function composition fg = map(f, g) @test fg(3) == ((36, 6), 4) fPLUSg = mapn(f, g) do x1, x2 x1 + x2 end @test fPLUSg(3) == (9+6, 4) fPRODg = @syntax_flatmap begin x1 = f x2 = g @pure x1 * x2 end @test fPRODg(3) == (9*6, 4) putget = @syntax_flatmap begin putstate(4) x = getstate @pure x * x end @test putget(()) == (16, 4) # FlipTypes # ========= # this only works because of the general `combine` implementation for State # so be cautious as the eltypes need to support `combine` to not get a MethodError in runtime a = State.([s -> (s, s), s -> (2s, s*s), s -> (s*s, 4)]) a2 = [map(x -> pure(Vector, x), v) for v in a] @test flip_types(a)(3) == ([3, 6, 81], 4)
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
1311
using TypeClasses using Test wait_a_little(f::Function, seconds=0.3) = @async begin sleep(seconds) f() end wait_a_little(x, seconds=0.3) = wait_a_little(() -> x, seconds) # Functor, Applicative, Monad # =========================== squared = map(wait_a_little(4)) do x x*x end; # returns a Task @test fetch(squared) == 16 @test typeof(mapn(+, wait_a_little(11), wait_a_little(12))) === Task @test fetch(mapn(+, wait_a_little(11), wait_a_little(12))) == 23 monadic = @syntax_flatmap begin a = wait_a_little(5) b = wait_a_little(a + 3) @pure a, b end; # returns a Task @test fetch(monadic) == (5, 8) @test fetch(pure(Task, 4)) == 4 # Monoid, Alternative # =================== @test fetch(wait_a_little("hello.") βŠ• wait_a_little("world.")) == "hello.world." @test fetch(wait_a_little(:a, 1.0) ⊘ wait_a_little(:b, 2.0)) == :a @test fetch(wait_a_little(:a, 3.0) ⊘ wait_a_little(:b, 2.0)) == :b @test fetch(wait_a_little(() -> error("fails"), 0.1) ⊘ wait_a_little(:succeeds, 0.3)) == :succeeds @test fetch(wait_a_little(:succeeds, 0.3) ⊘ wait_a_little(() -> error("fails"), 0.1)) == :succeeds @test_throws TaskFailedException fetch(wait_a_little(() -> error("fails1")) ⊘ wait_a_little(() -> error("fails2")) ⊘ wait_a_little(() -> error("fails3")) ⊘ wait_a_little(() -> error("fails4")))
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
109
@test ("hi", "b") βŠ• ("!", ".") == ("hi!", "b.") @test neutral(Tuple{String, String, String}) == ("", "", "")
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
1171
# MonoidAlternative # ================= a = Writer("a", [1]) b = Writer("b", [2,3,4]) # monoid is supported for convenience a βŠ• b == Writer("ab", [1,2,3,4]) # FunctorApplicativeMonad # ======================= @test eltype(Writer{Int, String}) == String @test map(x -> [x; x], a) == Writer("a", [1,1]) product_ab = Writer("ab", [1,2,3,4]) @test mapn(a, b) do x, y [x; y] end == product_ab h = @syntax_flatmap begin x = a y = b @pure [x; y] end @test h == product_ab @test pure(Writer{String}, 3) == Writer("", 3) # working with TypeClasses.pure @test (@syntax_flatmap begin a = pure(Writer{String}, 5) Writer("hi") @pure a end) == Writer("hi", 5) @test (@syntax_flatmap begin a = pure(Writer, 5) Writer(Option("hi")) @pure a end) == Writer(Option("hi"), 5) @test (@syntax_flatmap begin a = pure(Writer, 5) Writer("hi") @pure a end) == Writer("hi", 5) # FlipTypes # ========= v = Writer("first", [:a, :b, :c]) @test flip_types(v) == [Writer("first", :a), Writer("first", :b), Writer("first", :c)] vs = [Writer("first", :a), Writer("second", :b), Writer("third", :c)] @test flip_types(vs) == Writer("firstsecondthird", [:a, :b, :c])
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
134
using DataTypesBasic @test map(string, Const(4)) isa Const{Int} @test map(string, Const(4)).value == 4 @test eltype(Const(4)) == Any
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
1081
using Suppressor using TypeClasses using Test using DataTypesBasic state = Ref(0) mycontext = @ContextManager cont -> begin state[] += 1 returnvalue = cont(state[]) returnvalue end three_times = mapn(mycontext, mycontext, mycontext) do x, y, z (x, y, z) end @test three_times(x -> x) == (1,2,3) @test three_times(x -> x) == (4,5,6) @test state[] == 6 cm(i=4, prefix="") = @ContextManager function(cont) println("$(prefix)before $i") r = cont(i) println("$(prefix)after $i") r end cm2 = flatten(map(x -> cm(x*x), cm(4))) @test @suppress(cm2(x -> x)) == 16 @test splitln(@capture_out cm2(x -> x)) == [ "before 4", "before 16", "after 16", "after 4" ] nestedcm = @syntax_flatmap begin c1 = cm(1, "c1_") c2 = cm(c1 + 10, "c2_") @pure h = c1 + c2 c3 = cm(h + 100, "c3_") @pure (c1, c2, c3) end @test @suppress(nestedcm(x -> x)) == (1, 11, 112) @test splitln(@capture_out nestedcm(x -> x)) == [ "c1_before 1", "c2_before 11", "c3_before 112", "c3_after 112", "c2_after 11", "c1_after 1" ] @test pure(ContextManager, 3)(x -> x) == 3
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
1829
# MonoidAlternative # ================= # orelse @test Either{String, Int}("hi") ⊘ Either{String, Int}(1) == Either{String, Int}(1) @test Either{String, Int}("hi") ⊘ Either{String, Int}("ho") == Either{String, Int}("ho") @test Either{String, Int}(1) ⊘ Either{String, Int}(4) == Either{String, Int}(1) # combine @test_throws MethodError Either{Int}(true) βŠ• Either{Int}("ho") @test Either{Int, String}("hi") βŠ• Either{Int, String}("ho") == Either{Int, String}("hiho") @test Either{String, Int}("hi") βŠ• Either{String, Int}("ho") == Either{String, Int}("hiho") # FunctorApplicativeMonad # ======================= @test map(Either{String}(3)) do x x * x end == Either{String}(9) @test map(Either{String, Int}("hi")) do x x * x end == Either{String, Int}("hi") @test mapn(Either{String, Int}(2), Either{String, Int}("ho")) do x, y x + y end == Const("ho") # TODO we loose type information here, however it is tough to infer through the generic curry function constructed by mapn @test mapn(Either{String, Int}("hi"), Either{String, Int}(3)) do x, y x + y end == Const("hi") @test mapn(Either{String, Int}("hi"), Either{String, Int}("ho")) do x, y x + y end == Const("hi") he = @syntax_flatmap begin a = Either{String, Int}(2) b = Either{String, Int}(4) @pure a + b end @test he == Either{String}(6) h = @syntax_flatmap begin a = Either{String, Int}("hi") b = Either{String, Int}(4) @pure a + b end @test h == Either{String, Int}("hi") h = @syntax_flatmap begin a = Either{String, Int}(2) b = Either{String, Int}("ho") @pure a + b end @test h == Either{String, Int}("ho") @test pure(Either{String}, 3) == Identity(3) @test pure(Either, 3) == Identity(3) # FlipTypes # ========= @test flip_types(Const([1,2,3])) == Const.([1,2,3]) @test flip_types(Identity([1,2,3])) == Identity.([1,2,3])
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
605
# FunctorApplicativeMonad # ======================= @test map(Identity(3)) do x x + 4 end == Identity(3 + 4) @test mapn(Identity(3), Identity(4)) do x, y x + y end == Identity(3 + 4) @test pure(Identity, 5) == Identity(5) h = @syntax_flatmap begin x = Identity(3) y = Identity(4) @pure x + y end @test h == Identity(3 + 4) # MonoidAlternative # ================= @test neutral(Identity{String}) == Option() @test neutral(Identity) == Option() @test Identity("hi") βŠ• Identity("ho") == Identity("hiho") # FlipTypes # ======== @test flip_types(Identity([1,2,3,4])) == Identity.([1,2,3,4])
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
1131
using TypeClasses using DataTypesBasic using Test # MonoidAlternative # ================= @test neutral(Option) == Option(nothing) @test Option(3) ⊘ Option(4) == Option(3) # take the first non-nothing @test Option(nothing) ⊘ Option(4) == Option(4) # take the first non-nothing @test Option(nothing) ⊘ Option(4) == Option(4) # take the first non-nothing @test Option("hi") βŠ• Option("ho") == Option("hiho") # FunctorApplicativeMonad # ======================= @test map(Option(3)) do x x*x end == Option(9) @test map(Option(nothing)) do x x*x end == Option(nothing) @test mapn(Option(3), Option("hi")) do x, y "$x, $y" end == Option("3, hi") @test mapn(Option(3), Option(nothing)) do x, y "$x, $y" end == Option() ho = @syntax_flatmap begin a = Option(3) b = Option("hi") @pure "$a, $b" end @test ho == Option("3, hi") ho = @syntax_flatmap begin a = Option(3) b = Option(nothing) @pure "$a, $b" end @test ho == Option(nothing) @test pure(Option, 4) == Option(4) # FlipTypes # ========= @test flip_types(Identity([1,2,3])) == Identity.([1,2,3]) @test_throws MethodError flip_types(Const(nothing))
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
code
1696
# MonoidAlternative # ================= # combine Exceptions @test neutral(Exception) == MultipleExceptions() @test ErrorException("hi") βŠ• ErrorException("ho") == MultipleExceptions(ErrorException("hi"), ErrorException("ho")) # orelse Try @test Try(3) ⊘ Try(4) == Try(3) # take the first non-ErrorException("error") @test Try(ErrorException("error")) ⊘ Try(4) == Try(4) # take the first non-ErrorException("error") @test Try(ErrorException("error")) ⊘ Try(4) == Try(4) # take the first non-ErrorException("error") @test (@Try error("error")) ⊘ Try(4) == Try(4) # take the first non-ErrorException("error") # combine Try @test Try("hi") βŠ• Try("ho") == Try("hiho") @test Try(ErrorException("error")) βŠ• Try(4) == Try(4) @test Try(ErrorException("error")) βŠ• Try(ErrorException("exception")) == Try(MultipleExceptions(ErrorException("error"), ErrorException("exception"))) @test flip_left_right(Try(ErrorException("error"))) βŠ• flip_left_right(Try(ErrorException("exception"))) == flip_left_right(Try(MultipleExceptions(ErrorException("error"), ErrorException("exception")))) # FunctorApplicativeMonad # ======================= @test map(Try(3)) do x x*x end == Try(9) @test map(Try(ErrorException("error"))) do x x*x end == Try(ErrorException("error")) @test mapn(Try(3), Try("hi")) do x, y "$x, $y" end == Try("3, hi") @test mapn(Try(3), Try(ErrorException("error"))) do x, y "$x, $y" end isa Const{<:Exception} h = @syntax_flatmap begin a = Try(3) b = Try("hi") @pure "$a, $b" end @test h == Try("3, hi") h = @syntax_flatmap begin a = Try(3) b = Try(ErrorException("error")) @pure "$a, $b" end @test h == Try(ErrorException("error")) @test pure(Try, 4) == Try(4)
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
docs
6302
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [1.1.0] - 2021-07-23 ### Added - `neutral` can be used as generic `neutral` value. With this every Semigroup is automatically a Monoid. - `neutral(type)` now defaults to returning `neutral` instead of throwing a not-implemented-error. ### Changed - `pure(Writer, value)` now initializes the accumulator to `TypeClasses.neutral` instead of `Option()`, making it strictly more general with regard to `TypeClasses.combine`. ### Removed - `reduce_monoid`, `foldl_monoid` and `foldr_monoid` can now only be called as `reduce_monoid(iterable; [init])`. The older variant `reduce_monoid(combine_function, iterable; [init])` was a left over from previous thrown-away iterations. ## [1.0.0] - 2021-07-16 ### Added - extensive documentation is ready - re-exporting DataTypesBasic (Option, Try, Either, ContextManager) - `Writer` implements `neutral` and `combine` now, analog to `Pair` and `Tuple` - `Writer` implements `pure`, falling back to `Option()` as the generic neutral value. The user needs to wrap their accumulator into an `Option` to make use of this default. - new method `getaccumulator` is exported to access the accumulator of an `Writer`. Access its value with `Base.get`. - `Dictionaries.AbstractDictionary` is supported, however only loaded if Dictionaries is available, so no extra dependency. - `AbstractVector` type-class instances now generalises the previous `Vector` instances. - `Base.run` is now defined for `State` as an alias for just calling it - when running a `State` you now do not need to provide an initial state, in that case it defaults to `nothing`. - `β† ` operator is added, defined as `a β†  b = flatmap(_ -> b, a)`, and semantically kind of the reverse of `orelse`. - `β† `, `orelse` (`⊘`), `combine` (`βŠ•`) have now multi-argument versions (i.e. they can take more than 2 arguments). - added `flip_types` implementation for `Dict` - for convenience, `Base.map(f, a, b, c...)` is defined as an alias for `TypeClasses.mapn(f, a, b, c...)` for the data types `Option`, `Try`, `Either`, `ContextManager`, `Callable`, `Writer`, and `State`. - `Base.Nothing` now implements `neutral` and `combine`, concretely, `neutral(nothing) == nothing` and `nothing βŠ• nothing == nothing`. This was added to support `combine` on `Option` in general. ### Changed - `ap` has a default implementation now, using `flatmap` and `map`. This is added because most user will be easily familiar with `flatmap` and `map`, and can define those easily. Hence this fallback simplifies the usage massively. Also there is no method ambiguity threat, because `ap` dispatches on both the function and monad argument with the concrete type, so everything is safe. - changed `orelse` alias `βŠ›` to `⊘` for better visual separation, the latex name \\oslash which fits semantically kind of, and because the original reasoning was an misunderstanding. - `Task` and `Future` now have an `orelse` implementation which parallelizes runs and returns the first result - `flatmap` for `Identity` is now defined as `flatmap(f, a::Identity) = f(a.value)`, i.e. there is no call to `convert(Identity, ...)` any longer, which makes composing Monads even simpler (Furthermore this gets rid of the need of converting a `Const` to an `Identity` which was more a hack beforehand). - `neutral` for `Identity` now always returns `Const(nothing)`. - updated TagBot - updated CompatHelper ### Fixed - `neutral` for Either now returns `Const`, which is accordance to the Monoid laws. ### Removed - `orelse` is no longer forwarded to inner elements, as this function is usually defined on a container level. ## [0.6.1] - 2021-03-30 ### Added * CI/CD pipeline * Minimal Docs using Documenter * Codecovering * TagBot & CompatHelper * License ### Changed * parts from the README went to the docs ## [0.6.0] - 2021-03-29 ### Removed * Trait functions have been removed. I.e. there is no longer isMonad or isApplicative. The reason is that there is ongoing work on inferring such traits automatically from whether a function is defined or not. As soon as such a generic util exists, the traits would not be needed anylonger. In addition we experienced ambiguities with isSemigroup and isMonoid, because for some examples, the trait affiliation would be defined by the eltype, but eltype is an instable characteristic and hence not recommended to use. We circumvent this problem for now by just not providing the traits. * Removed dependency on WhereTraits.jl. This makes the package for more independent and easier to maintain. We loose some flexibility in multiple dispatch, and instead assume stronger constraints on how the functions should be used. * Removed `absorbing` function. It was no where really used. To simplify maintenance we take it out for now. * Removed `change_eltype` function During the development of this package we initially used a further function, quite related to `eltype`, called `change_eltype`. It took a container type like `Vector` and tried to change its ElementType, e.g. `change_eltype(Vector{Int}, String) == Vector{String}`. While this may seem intuitively reasonable for example to define `isAp`, namely to check whether for some Container `Container` the key function `ap` is defined for `ap(::Container{Function}, ::Container)`, this is a version of dispatching on `eltype` and hence should be avoided. The resolution is that we assume `ap` is always overloaded with the first argument being of the general Container-type, i.e. without any restrictions to the eltype. ### Changed - Writer no longer checks whether the accumulator defines the Semigroup interface. This is because we dropped the traits function isSemigroup. ## [0.5.0] - 2020-03-23 ### Added * TypeClasses: Functor, Applicative, Monads, Semigroup, Monoid and flip_types (traversable sequence) * new DataTypes: Iterable, Callable, Writer, State * TypeInstances: Iterable, Callable, Writer, State, Future, Task, Tuple, Pair, String, Vector, Dict * TypeInstances for all of DataTypesBasic.jl: Const, Identity, Either, ContextManager
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
docs
2203
# TypeClasses.jl [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://JuliaFunctional.github.io/TypeClasses.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://JuliaFunctional.github.io/TypeClasses.jl/dev) [![Build Status](https://github.com/JuliaFunctional/TypeClasses.jl/workflows/CI/badge.svg)](https://github.com/JuliaFunctional/TypeClasses.jl/actions) [![Coverage](https://codecov.io/gh/JuliaFunctional/TypeClasses.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/JuliaFunctional/TypeClasses.jl) TypeClasses defines general programmatic abstractions taken from Scala cats and Haskell TypeClasses. The following interfaces are defined: | TypeClass | Methods | Description | | ------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | | Functor | `Base.map` | The basic definition of a container or computational context. | | Applicative | Functor &`TypeClasses.ap` | Computational context with support for parallel execution. | | Monad | Applicative &`TypeClasses.flatmap` | Computational context with support for sequential, nested execution. | | Semigroup | `TypeClasses.combine`, alias `βŠ•` | The notion of something which can be combined with other things of its kind. | | Monoid | Semigroup &`TypeClasses.neutral` | A semigroup with a neutral element is called a Monoid, an often used category. | | Alternative | `TypeClasses.neutral` & `TypeClasses.orelse`, alias `⊘` | Slightly different than Monoid, the`orelse` semantic does not merge two values, but just takes one of the two. |
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
docs
2054
```@meta CurrentModule = TypeClasses DocTestSetup = quote using TypeClasses end ``` # TypeClasses.jl Documentation for [TypeClasses](https://github.com/JuliaFunctional/TypeClasses.jl). TypeClasses defines general programmatic abstractions taken from Scala cats and Haskell TypeClasses. The following interfaces are defined: TypeClass | Methods | Description ----------- | ----------------------------------- | -------------------------------------------------------------------- [Functor ](@ref functor_applicative_monad) | `Base.map` | The basic definition of a container or computational context. [Applicative](@ref functor_applicative_monad) | Functor & `TypeClasses.pure` & `TypeClasses.ap` (automatically defined when `map` and `flatmap` are defined) | Computational context with support for parallel execution. [Monad](@ref functor_applicative_monad) | Applicative & `TypeClasses.flatmap` | Computational context with support for sequential, nested execution. [Semigroup](@ref semigroup_monoid_alternative) | `TypeClasses.combine`, alias `βŠ•` | The notion of something which can be combined with other things of its kind. [Monoid](@ref semigroup_monoid_alternative) | Semigroup & `TypeClasses.neutral` | A semigroup with a neutral element is called a Monoid, an often used category. [Alternative](@ref semigroup_monoid_alternative) | `TypeClasses.neutral` & `TypeClasses.orelse`, alias `⊘` | Slightly different than Monoid, the `orelse` semantic does not merge two values, but just takes one of the two. [FlipTypes](@ref flip_types) | `TypeClasses.flip_types` | Enables dealing with nested types. Transforms an `A{B{C}}` into an `B{A{C}}`. For convenience this packages further provides a couple of standard DataTypes and implements the interfaces for them. ## Manual Outline ```@contents Pages = ["manual.md", "manual-TypeClasses.md", "manual-DataTypes.md"] ``` ## [Library Index](@id main-index) ```@index Pages = ["library.md"] ```
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
docs
853
# TypeClasses Public API ## Functor, Applicative, Monad ```@meta CurrentModule = TypeClasses ``` Foreach, using `Base.foreach` ```@docs @syntax_foreach ``` Functor, using `Base.map` ```@docs @syntax_map ``` Applicative Core ```@docs pure ap ``` Applicative Helper ```@docs mapn @mapn tupled ``` Monad Core ```@docs flatmap ``` Monad Helper ```@docs flatten β†  @syntax_flatmap ``` ## Semigroup, Monoid, Alternative Semigroup ```@docs combine βŠ• ``` Neutral ```@docs neutral ``` Monoid Helpers ```@docs reduce_monoid foldr_monoid foldl_monoid ``` Alternative ```@docs orelse ⊘ ``` ## FlipTypes ```@docs flip_types default_flip_types_having_pure_combine_apEltype ``` ## TypeClasses.DataTypes Iterable ```@docs Iterable ``` Callable ```@docs Callable ``` Writer ```@docs Writer getaccumulator ``` State ```@docs State getstate putstate ```
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git
[ "MIT" ]
1.1.0
c47d617be00391c09bbe2f0f093b4a364ff06ed2
docs
24747
```@meta CurrentModule = TypeClasses DocTestSetup = quote using TypeClasses using Dictionaries end ``` # DataTypes ## Option, Try, Either `Option`, `Try`, and `Either` are re-exported from [DataTypesBasic.jl](https://github.com/JuliaFunctional/DataTypesBasic.jl) and equipped with the TypeClasses. As all three are implemented using the same primitives `Identity` and `Const`, they can actually be combined seamlessly. `Option` and `Try` are really only more specific `Either`. This is quite a unique design among typeclasses, which enables a lot flexibility and simplicity. DataType | Implementation | Helpers -------- | -------------- | ------- Identity | `Identity` | `isidentity`, all&nbsp;TypeClasses Const | `Const` | `Base.isconst`, almost all TypeClasses, but without `pure` Either | `Either{L, R} = Union{Const{L}, Identity{R}}` | `Either`, `Base.eltype`, `either`, `@either`, `flip_left_right`, `iseither`, `isleft`, `isright`, `getleft`, `getright`, `getleftOption`, `getrightOption`, `getOption`, all&nbsp;TypeClasses Try | `Try{T} = Union{Const{<:Exception}, Identity{T}}` | `Try`, `@Try`, `@TryCatch`, `istry`, `issuccess`, `isfailure`, all&nbsp;TypeClasses Option | `Option{T} = Union{Const{Nothing}, Identity{T}}` | `Option`, `isoption`, `issome`, `isnone`, `iffalse`, `iftrue`, all&nbsp;TypeClasses For more Details take also a look at [DataTypesBasic.jl](https://github.com/JuliaFunctional/DataTypesBasic.jl). ### Functor/Applicative/Monad If all works, the result is an `Identity` ```jldoctest julia> @syntax_flatmap begin a = true ? Option(4) : Option() b = @Try isodd(a) ? error("stop") : 5 c = either(:left, isodd(b), "right") @pure a, b, c end Identity((4, 5, "right")) ``` If something fails, the computation stops early on, returning a `Const` ```jldoctest julia> @syntax_flatmap begin a = false ? Option(4) : Option() b = @Try isodd(a) ? error("stop") : 5 c = either(:left, isodd(b), "right") @pure a, b, c end Const(nothing) julia> @syntax_flatmap begin a = true ? Option(5) : Option() b = @Try isodd(a) ? error("stop") : 5 c = either(:left, isodd(b), "right") @pure a, b, c end Const(Thrown(ErrorException("stop"))) julia> @syntax_flatmap begin a = true ? Option(4) : Option() b = @Try isodd(a) ? error("stop") : 6 c = either(:left, isodd(b), "right") @pure a, b, c end Const(:left) ``` ### Monoid/Alternative You can also `combine` Option, Try, Either. When combining Const with Const or Identity with Identity, the `combine` function of the underlying value is used. When combining `Const` with `Identity`, the `Identity` is always returned. When using `Option`, the value `Option() = Const(nothing)` deals as the `neutral` value and hence you can make any Semigroup (something which supports `combine`) into a Monoid (something which supports `combine` and `neutral`) by just wrapping it into `Option`. ```jldoctest julia> combine(Option(), Option(4)) Identity(4) julia> @Try(4) βŠ• @Try(error("stop")) # \oplus is an alias for `combine` Identity(4) julia> either(:left, true, "right.") βŠ• @Try("success.") βŠ• Option("also needs to be a string.") Identity("right.success.also needs to be a string.") ``` If your the element does not support `combine`, you can still use `orelse` (alias `⊘`, \oslash), which will just return the first Identity value. ```jldoctest julia> either(:left, false, "right.") ⊘ @Try("success.") ⊘ Option(["does" "not" "need" "to" "be" "a" "string."]) Identity("success.") ``` For completenes, the Monad definition of `Option`, `Try`, and `Either` also come with the binary operator `β† ` (\twoheadrightarrow), which acts somehow as the reverse of `orelse`: It will stop at the first `Const` value: ```jldoctest julia> either(:left, true, "right.") β†  @Try(error("stop.")) β†  Option(["does" "not" "need" "to" "be" "a" "string."]) Const(Thrown(ErrorException("stop."))) ``` ### FlipTypes With any Functor you can flip types. ```jldoctest julia> flip_types(Const(Identity(3))) Identity(Const(3)) julia> flip_types(Identity(Const(3))) Const(3) ``` You may be surprised by `Const(3)`, however this is correct. Flipping an outer Identity will `map` Identity over the inner Functor. The `Const` Functor, however, just ignores everything when mapped over it and will stay the same. More correctly, it would have changed its pseudo return value, however this is not represented in Julia, leaving it literally constant. ## ContextManager `ContextManager` also comes from [DataTypesBasic.jl](https://github.com/JuliaFunctional/DataTypesBasic.jl). It is super handy to define your own enter-exit semantics. ### Functor/Applicative/Monad ```jldoctest julia> create_context(x) = @ContextManager continuation -> begin println("before x = $x") result = continuation(x) println("after x = $x") result end create_context (generic function with 1 method) julia> context = @syntax_flatmap begin a = create_context(3) b = create_context(a*a) @pure a, b end; julia> context() do x println("within x = $x") x end before x = 3 before x = 9 within x = (3, 9) after x = 9 after x = 3 (3, 9) ``` ### Monoid/Alternative ContextManager only supports Functor/Applicative/Monad TypeClasses. ### FlipTypes ContextManager only supports Functor/Applicative/Monad TypeClasses. ## AbstractVector `Base.Vector` are supported. More concretely, methods are implemented for the whole `AbstractArray` tree, by converting from `Vector`. Vector types can be seamlessly combined with `Either` (including `Options` and `Try`), providing a very flexible setup out-of-the-box. `Either` types get converted to singleton lists in the case of `Identity` or an empty list in the case of `Const`. ### Functor/Applicative/Monad The implementation of `TypeClasses.flatmap` follows the flattening/combining semantics, which takes all combinations of the vectors. As if you would have used for loops, however with constructing a result by collecting everything. ```jldoctest julia> @syntax_flatmap begin a = [1, 2] b = [:x, :y] @pure a, b end 4-element Vector{Tuple{Int64, Symbol}}: (1, :x) (1, :y) (2, :x) (2, :y) julia> @syntax_flatmap begin a = [1, 2, 3, 4, 5] @pure b = a + 1 c = iftrue(a % 2 == 0) do a + b end @Try @assert a > 3 @pure @show a, b, c end (a, b, c) = (4, 5, 9) 1-element Vector{Any}: (4, 5, 9) ``` Sometimes it may also be handy to use the `pure` function. ```jldoctest julia> pure(Vector, 1) 1-element Vector{Int64}: 1 ``` ### Monoid/Alternative Vectors only support Monoid interface, no Alternative. ```jldoctest julia> neutral(Vector) Any[] julia> [1] βŠ• [5,6] 3-element Vector{Int64}: 1 5 6 julia> combine([1], [5, 6]) 3-element Vector{Int64}: 1 5 6 julia> foldl_monoid([[1,2], [4,5], [10]]) 5-element Vector{Int64}: 1 2 4 5 10 ``` ### FlipTypes You can flip nested types with `Vector`. It assumes the inner type supports Applicative method `ap` (if you have defined `flatmap` the `ap` method is automatically defined for you). ```jldoctest julia> flip_types([Option(1), Option("2"), Option(:three)]) Identity(Any[1, "2", :three]) julia> flip_types([Option(1), Option(), Option(:three)]) Const(nothing) ``` Remember that flip_types usually forgets information, like here in the case when a `Const` is found. ## Dict We do not support `AbstractDict` in general, because there is no common way of constructing such dicts. For the concrete `Base.Dict` we know how to construct it. ### Functor/Applicative/Monad `Base.map` explicitly throws an error on `Dict`, so there is no way to support Functor/Applicative/Monad typeclasses. ### Monoid/Alternative `neutral` for Dict just returns a general empty Dict ```jldoctest julia> neutral(Dict) Dict{Any, Any}() ``` `combine` (`βŠ•`) will forward the function call `combine` to its elements. `orelse` (`⊘`) will take the first existing value, i.e. a flipped version of merge. ```jldoctest julia> d1 = Dict(:a => "3", :b => "1") Dict{Symbol, String} with 2 entries: :a => "3" :b => "1" julia> d2 = Dict(:a => "5", :b => "9", :c => "15") Dict{Symbol, String} with 3 entries: :a => "5" :b => "9" :c => "15" julia> d1 βŠ• d2 Dict{Symbol, String} with 3 entries: :a => "35" :b => "19" :c => "15" julia> d1 ⊘ d2 Dict{Symbol, String} with 3 entries: :a => "3" :b => "1" :c => "15" ``` ### FlipTypes `flip_types` works only in one direction. ```jldoctest julia> flip_types(Dict(:a => [1,2], :b => [3, 4])) 4-element Vector{Dict{Symbol, Int64}}: Dict(:a => 1, :b => 3) Dict(:a => 1, :b => 4) Dict(:a => 2, :b => 3) Dict(:a => 2, :b => 4) julia> flip_types([Dict(:a => 1, :b => 3), Dict(:a => 2, :b => 4)]) ERROR: map is not defined on dictionaries ``` As you see, this is becaue `Base.map` explicitly throws an Error for `Base.Dict`. ## AbstractDictionary Luckily this limitation of `Base.Dict` can be circumvented by using the package `Dictionaries` which enhances the dictionary interface and speeds up its performance. ### Functor/Applicative/Monad `AbstractDictionary` is the abstract type provided by the package, and it already defines `Base.map` for it, so that we can implement Functor/Applicative/Monad interfaces on top. The semantics of the flattening of dictionaries follows the implementation in Scala Cats for Scala's Map type. It works like first filtering for common keys and then doing stuff respectively. ```jldoctest julia> using Dictionaries julia> dict = Dictionary(["a", "b", "c"], [1, 2, 3]) 3-element Dictionaries.Dictionary{String, Int64} "a" β”‚ 1 "b" β”‚ 2 "c" β”‚ 3 julia> create_dictionary(x) = Dictionary(["b", "c", "d"], [10x, 20x, 30x]) create_dictionary (generic function with 1 method) julia> @syntax_flatmap begin a = dict b = create_dictionary(a) @pure a, b end 2-element Dictionaries.Dictionary{String, Tuple{Int64, Int64}} "b" β”‚ (2, 20) "c" β”‚ (3, 60) ``` 20 is 10 times 2, and 60 is 20 times 3. You see it picks the right values for "b" and "c" respectively. The key "d" does not exist in all dictionaries and hence is filtered out. ### Monoid/Alternative The implementation for `neutral`, `combine` and `orelse` are analogous to those for `Dict`, just a bit more abstract. Thanks to the good interfaces defined in the package `Dictionaries`, we can support general `AbstractDictionary`. ### FlipTypes `flip_types` now actually works in both directions, as `AbstractDictionary` is a Monad itself. ```jldoctest julia> flip_types(dictionary((:a => [1,2], :b => [3, 4]))) 4-element Vector{Dictionary{Symbol, Int64}}: {:a = 1, :b = 3} {:a = 1, :b = 4} {:a = 2, :b = 3} {:a = 2, :b = 4} julia> flip_types([ dictionary((:a => 1, :b => 2)), dictionary((:a => 10, :b => 20)), dictionary((:b => 200, :c => 300)) ]) 1-element Dictionaries.Dictionary{Symbol, Vector{Int64}} :b β”‚ [2, 20, 200] ``` In the last example you can again recognize the filtering logic. Here it leaves `:b` as the only valid key. ## Iterable TypeClasses exports a wrapper type called `Iterable` which can be used to enable support on any iterable. ### Functor/Applicative/Monad ```jldoctest julia> collect(@syntax_flatmap begin a = Iterable(1:2) b = Iterable([3,6]) @pure a, b end) 4-element Vector{Tuple{Int64, Int64}}: (1, 3) (1, 6) (2, 3) (2, 6) ``` The `@syntax_flatmap` macro actually can receive a wrapper function as an additional first argument with which the above can be written as ```jldoctest julia> collect(@syntax_flatmap Iterable begin a = 1:2 b = [3,6] @pure a, b end) 4-element Vector{Tuple{Int64, Int64}}: (1, 3) (1, 6) (2, 3) (2, 6) ``` You can use `TypeClasses.pure` to construct singleton Iterables ```jldoctest julia> pure(Iterable, 1) Iterable{TypeClasses.DataTypes.Iterables.IterateSingleton{Int64}}(TypeClasses.DataTypes.Iterables.IterateSingleton{Int64}(1)) ``` It wraps an internal type which really just supports the singleton Iterable for your convenience. ### Monoid/Alternative `Iterable` defines only the Monoid interface, just like Vector, but lazy. ```jldoctest julia> Iterable(1:2) βŠ• Iterable(5:6) Iterable{Base.Iterators.Flatten{Tuple{UnitRange{Int64}, UnitRange{Int64}}}}(Base.Iterators.Flatten{Tuple{UnitRange{Int64}, UnitRange{Int64}}}((1:2, 5:6))) julia> collect(Iterable(1:2) βŠ• Iterable(5:6)) 4-element Vector{Int64}: 1 2 5 6 ``` For implementing the `neutral` function, an extra type for an empty iterator was defined within TypeClasses. It is itself not exported, because using `neutral` instead is simpler and better. ```jldoctest julia> neutral(Iterable) Iterable{TypeClasses.DataTypes.Iterables.IterateEmpty{Union{}}}(TypeClasses.DataTypes.Iterables.IterateEmpty{Union{}}()) julia> collect(neutral(Iterable)) Union{}[] ``` The element-type is `Union{}` to be easily type-joined with other iterables and element-types. ### FlipTypes Again similar to Vector, Iterables define `flip_types` in a lazy style. ```jldoctest julia> it = Iterable(Option(i) for i ∈ [1, 4, 7]) Iterable{Base.Generator{Vector{Int64}, Type{Option{T} where T}}}(Base.Generator{Vector{Int64}, Type{Option{T} where T}}(Option{T} where T, [1, 4, 7])) julia> flip_types(it) Identity(Iterable{Base.Iterators.Flatten{Tuple{Base.Iterators.Flatten{Tuple{TypeClasses.DataTypes.Iterables.IterateSingleton{Int64}, TypeClasses.DataTypes.Iterables.IterateSingleton{Int64}}}, TypeClasses.DataTypes.Iterables.IterateSingleton{Int64}}}}(Base.Iterators.Flatten{Tuple{Base.Iterators.Flatten{Tuple{TypeClasses.DataTypes.Iterables.IterateSingleton{Int64}, TypeClasses.DataTypes.Iterables.IterateSingleton{Int64}}}, TypeClasses.DataTypes.Iterables.IterateSingleton{Int64}}}((Base.Iterators.Flatten{Tuple{TypeClasses.DataTypes.Iterables.IterateSingleton{Int64}, TypeClasses.DataTypes.Iterables.IterateSingleton{Int64}}}((TypeClasses.DataTypes.Iterables.IterateSingleton{Int64}(1), TypeClasses.DataTypes.Iterables.IterateSingleton{Int64}(4))), TypeClasses.DataTypes.Iterables.IterateSingleton{Int64}(7))))) julia> map(collect, flip_types(it)) Identity([1, 4, 7]) ``` ## Callable We also provide a wrapper for functions. To enable support for your functions, just wrap them into `Callable`. ### Functor/Applicative/Monad The callable monad is also sometimes called reader monad, however in Julia context that name doesn't make much sense. At least you heard it and can connect the concepts. ```jldoctest julia> func = @syntax_flatmap begin a = Callable(x -> x * 10) b = Callable(x -> x * 100 ) Callable() do x x + a + b end end; julia> func(2) 222 ``` Similar as for Iterables, it may simplify your setup to add `Callable` as a wrapper-function to `@syntax_flatmap` ```jldoctest julia> func = @syntax_flatmap Callable begin # you need to use anonymous functions, as the equal sign `=` is rewritten by the macro a = x -> x * 10 b = x -> x * 100 identity() do x x + a + b end end; julia> func(3) 333 ``` You can also wrap a value into `Callable` using `pure`. It works like a constant function. ```jldoctest julia> pure(Callable, 1)() 1 julia> pure(Callable, 1)("any", :arguments, key=4) 1 ``` ### Monoid/Alternative `Callables` implement only `combine` by forwarding it to its elements. ```jldoctest julia> a = Callable(x -> "hello $x"); julia> b = Callable(x -> "!"); julia> (a βŠ• b)(:Albert) "hello Albert!" ``` ### FlipTypes Callable itself does not implement `flip_types` as it would need to know its arguments in advance, which of course is impossible. However because it implements Monad interface, we can use it as a nested type within another type and get it out. ```jldoctest julia> a = Callable.([x -> x, y -> 2y, z -> z*z]); julia> flip_types(a)(3) 3-element Vector{Int64}: 3 6 9 ``` ## `@spawnat` and `@async` `@async` runs the computation in another thread, `@spawnat` runs it on another machine potentially. Both are supported by TypeClasses. `@async` are described by `Task` objects, `@spawnat` by `Distributed.Future` respectively. Both kinds of contexts can be evaluated/run with `Base.fetch`. ### Functor/Applicative/Monad ```jldoctest taskfuture julia> wait_a_little(f::Function, seconds=0.3) = @async begin sleep(seconds) f() end wait_a_little (generic function with 2 methods) julia> wait_a_little(x, seconds=0.3) = wait_a_little(() -> x, seconds) wait_a_little (generic function with 4 methods) julia> squared = map(wait_a_little(4)) do x x*x end; # returns a Task julia> fetch(squared) 16 julia> fetch(mapn(+, wait_a_little(11), wait_a_little(12))) 23 julia> monadic = @syntax_flatmap begin a = wait_a_little(5) b = wait_a_little(a + 3) @pure a, b end; # returns a Task julia> fetch(monadic) (5, 8) ``` You can do the very same using `@spawnat`, i.e. the type `Distributed.Future`. Just use the following function instead. ```julia using Distributed wait_a_little(f::Function, seconds=0.3) = @spawnat :any begin sleep(seconds) f() end ``` You can put any value into a `Task` and `Future` object by using `TypeClasses.pure`. You get it out again with `Base.fetch`. ```jldoctest julia> fetch(pure(Task, 4)) 4 julia> using Distributed julia> fetch(pure(Future, "a")) "a" ``` ### Monoid/Alternative Future and Task do not implement `neutral`. `combine` is forwarded to the computation results. ```jldoctest taskfuture julia> fetch(wait_a_little("hello.") βŠ• wait_a_little("world.")) "hello.world." ``` `orelse` is defined as the Alternative semantics of running multiple threads in parallel and taking the faster one. ```jldoctest taskfuture julia> fetch(wait_a_little(:a, 1.0) ⊘ wait_a_little(:b, 2.0)) :a julia> fetch(wait_a_little(:a, 3.0) ⊘ wait_a_little(:b, 2.0)) :b julia> fetch(wait_a_little(() -> error("fails"), 0.1) ⊘ wait_a_little(:succeeds, 0.3)) :succeeds julia> fetch(wait_a_little(:succeeds, 0.3) ⊘ wait_a_little(() -> error("fails"), 0.1)) :succeeds ``` In case all different paths fail, all errors are collected into an `MultipleExceptions` object ```julia taskfuture julia> fetch(wait_a_little(() -> error("fails1")) ⊘ wait_a_little(() -> error("fails2")) ⊘ wait_a_little(() -> error("fails3")) ⊘ wait_a_little(() -> error("fails4"))) ERROR: TaskFailedException Stacktrace: [1] wait @ ./task.jl:322 [inlined] [2] fetch(t::Task) @ Base ./task.jl:337 [3] top-level scope @ REPL[56]:1 nested task error: MultipleExceptions{NTuple{4, Thrown{TaskFailedException}}}((Thrown(TaskFailedException(Task (failed) @0x00007f5c8633af50)), Thrown(TaskFailedException(Task (failed) @0x00007f5c8633b0a0)), Thrown(TaskFailedException(Task (failed) @0x00007f5c864382b0)), Thrown(TaskFailedException(Task (failed) @0x00007f5c86438550)))) ``` You can do the very same using `@spawnat`, i.e. the type `Distributed.Future`. Just use the following function instead. ```julia using Distributed wait_a_little(f::Function, seconds=0.3) = @spawnat :any begin sleep(seconds) f() end ``` Note that a fetch on a Future will RETURN an RemoteException object instead of throwing an error. ```julia julia> fetch(wait_a_little(() -> error("fails1")) ⊘ wait_a_little(() -> error("fails2")) ⊘ wait_a_little(() -> error("fails3")) ⊘ wait_a_little(() -> error("fails4"))) RemoteException(1, CapturedException(MultipleExceptions{NTuple{4, RemoteException}}((RemoteException(1, CapturedException(ErrorException("fails1"), [...] ``` ### FlipTypes Implementing `flip_types` does not make much sense for `Task` and `Future`, as this would need to execute the Task, and map over its returned value, finally creating a bunch of dummy Tasks within it. `@async` and `@spawnat` are really meant to be lazy constructions. ## Writer The `Writer{Accumulator, Value}` monad stores logs or other intermediate outputs. It is like `Base.Pair{Accumulator, Value}`, with the added assumption that `Accumulator` implements the `TypeClasses.combine`. Also the `eltype` of a `Writer` corresponds to the element-type of the `Value`. ### Functor/Applicative/Monad You can use the writer to implicitly accumulate any Semigroup or Monoid ```jldoctest julia> @syntax_flatmap begin a = pure(Writer{String}, 5) Writer("first.") b = Writer("second.", a*a) @pure a, b end Writer{String, Tuple{Int64, Int64}}("first.second.", (5, 25)) ``` In case you only have a Semigroup, no problem, as the default `TypeClasses.pure` implementation for writer will use `neutral` as the accumulator, which combines with everything. ```jldoctest julia> @syntax_flatmap begin a = pure(Writer, 5) Writer("hi") @pure a end Writer{String, Int64}("hi", 5) ``` ### Monoid/Alternative `neutral` and `combine` will foward the call to `neutral` and `combine` onto the element-types (for `neutral`) or the concrete element-values (for `combine`). ```jldoctest julia> neutral(Writer{Option, Vector}) Const(nothing) => Any[] julia> Writer("one.", [1,2]) βŠ• Writer("two.", [3,4]) βŠ• Writer("three.", [5]) Writer{String, Vector{Int64}}("one.two.three.", [1, 2, 3, 4, 5]) julia> Writer("hello.") βŠ• Writer("world.") # the single argument constructor is just for logging, however as `nothing` always combines, this works too Writer{String, Nothing}("hello.world.", nothing) ``` We do not implement `orelse`, as it is commonly meant on container level, but there is no obvious failure semantics here. ### FlipTypes `Writer` supports `flip_types` by duplicating the accumulator respectively. ```jldoctest julia> flip_types(Writer("accumulator", [1, 2, 3])) 3-element Vector{Writer{String, Int64}}: Writer{String, Int64}("accumulator", 1) Writer{String, Int64}("accumulator", 2) Writer{String, Int64}("accumulator", 3) ``` Used within another FlipTypes, `Writer` just accumulates the accumulator. ```jldoctest julia> flip_types([ Writer("one.", 1), Writer("two.", 2), Writer("three.", 3) ]) Writer{String, Vector{Int64}}("one.two.three.", [1, 2, 3]) ``` ## Pair/Tuple Pair and Tuple have no Monad instances, but we support `combine` and `neutral` by forwarding the calls to its elements ### Functor/Applicative/Monad No implementation. Please see [Writer](@ref) instead. ### Monoid/Alternative ```jldoctest julia> ("hello." => [1,2]) βŠ• ("world." => [3]) "hello.world." => [1, 2, 3] julia> ("hello.", [1,2], Dict(:a => "one.")) βŠ• ("world.", [3], Dict(:a => "two.")) ("hello.world.", [1, 2, 3], Dict(:a => "one.two.")) julia> neutral(Pair{String, Vector}) "" => Any[] julia> neutral(Tuple{String, Vector}) ("", Any[]) julia> neutral(Tuple{String}) ("",) ``` ### FlipTypes No implementation. Please see [Writer](@ref) instead. ## State With the `State` monad you can hide the modification of some external variable. In Julia you can modify variables by side-effect, hence this State monad is rather for illustrative purposes only. However if you like to have tight control over your state or config, you can give it a try. ### Functor/Applicative/Monad You can lift an arbitrary value into a `State` with `TypeClasses.pure`. It won't do anything with the state. ```jldoctest julia> run(pure(State, "returnvalue"), :initialstate) ("returnvalue", :initialstate) ``` If you want to change the state, use `TypeClasses.putstate`, and if you want to access the state itself, you can use `TypeClasses.getstate`. For the general case you can construct `State` by passing a function taking the state as its only input argument, and returning result value and new state in a tuple. ```jldoctest julia> putget = @syntax_flatmap begin putstate(4) x = getstate State(s -> ("x = $x", s+1)) end; julia> value, state = putget(()) ("x = 4", 5) ``` ### Monoid/Alternative State only supports `combine` by forwarding it to its inner element. The state is passed from the first to the second. ```jldoctest julia> state1 = State(s -> ("one.", s*s)); julia> state2 = State(s -> ("two.", 2s)); julia> run(state1 βŠ• state2, 3) ("one.two.", 18) julia> run(state2 βŠ• state1, 3) ("two.one.", 36) ``` ### FlipTypes There is no implementation for `flip_types`, as you would need to look inside the `State` and wrap it out. That is hidden behind a function which depends on the state, so no way to bring things inside-out without such a state.
TypeClasses
https://github.com/JuliaFunctional/TypeClasses.jl.git