Skip to content

Commit bc70137

Browse files
committed
allow more types in Extrema
1 parent e32e0e2 commit bc70137

2 files changed

Lines changed: 15 additions & 4 deletions

File tree

src/stats/stats.jl

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -361,18 +361,25 @@ Maximum and minimum.
361361
maximum(o)
362362
minimum(o)
363363
"""
364+
# T is type to store data, S is type of single observation.
365+
# E.g. you may want to accept any Number even if you are storing values as Float64
364366
mutable struct Extrema{T,S} <: OnlineStat{S}
365367
min::T
366368
max::T
367369
n::Int
370+
function Extrema(T::Type = Float64)
371+
a, b, S = extrema_init(T)
372+
new{T,S}(a, b, 0)
373+
end
368374
end
369-
Extrema(T::Type{<:Number} = Float64) = Extrema{T,Number}(typemax.(T), typemin.(T), 0)
370-
Extrema(T::Type) = Extrema{T,T}(typemax.(T), typemin.(T), 0)
371-
Extrema(initmin::T, initmax::T) where {T} = Extrema{T}(initmin, initmax, 0)
375+
extrema_init(T::Type{<:Number}) = typemax(T), typemin(T), Number
376+
extrema_init(T::Type{String}) = "", "", String
377+
extrema_init(T::Type{Date}) = typemax(Date), typemin(Date), Date
378+
extrema_init(T::Type) = rand(T), rand(T), T
372379
function _fit!(o::Extrema, y)
380+
(o.n += 1) == 1 && (o.min = o.max = y)
373381
o.min = min(o.min, y)
374382
o.max = max(o.max, y)
375-
o.n += 1
376383
end
377384
function _merge!(o::Extrema, o2::Extrema)
378385
o.min = min(o.min, o2.min)

test/runtests.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,10 @@ end
116116
o = fit!(Extrema(Date), Date(2010):Day(1):Date(2011))
117117
@test minimum(o) == Date(2010)
118118
@test maximum(o) == Date(2011)
119+
120+
@test value(fit!(Extrema(Char), 'a':'z')) == ('a', 'z')
121+
@test value(fit!(Extrema(Char), "abc")) == ('a', 'c')
122+
@test value(fit!(Extrema(String), ["a", "b"])) == ("a", "b")
119123
end
120124
#-----------------------------------------------------------------------# Fit[Dist]
121125
@testset "Fit[Dist]" begin

0 commit comments

Comments
 (0)