Skip to content

Commit 0413ef0

Browse files
authored
Fix type-instability of ∘ and Some when wrapping types (#35980)
1 parent dd3f173 commit 0413ef0

File tree

5 files changed

+26
-1
lines changed

5 files changed

+26
-1
lines changed

base/operators.jl

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -873,10 +873,26 @@ julia> ∘(fs...)(3)
873873
```
874874
"""
875875
function end
876+
877+
struct ComposedFunction{F,G} <: Function
878+
f::F
879+
g::G
880+
ComposedFunction{F, G}(f, g) where {F, G} = new{F, G}(f, g)
881+
ComposedFunction(f, g) = new{Core.Typeof(f),Core.Typeof(g)}(f, g)
882+
end
883+
884+
(c::ComposedFunction)(x...) = c.f(c.g(x...))
885+
876886
(f) = f
877-
(f, g) = (x...)->f(g(x...))
887+
(f, g) = ComposedFunction(f, g)
878888
(f, g, h...) = (f g, h...)
879889

890+
function show(io::IO, c::ComposedFunction)
891+
show(io, c.f)
892+
print(io, "")
893+
show(io, c.g)
894+
end
895+
880896
"""
881897
!f::Function
882898

base/show.jl

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ function show(io::IO, ::MIME"text/plain", f::Function)
4444
end
4545
end
4646

47+
show(io::IO, ::MIME"text/plain", c::ComposedFunction) = show(io, c)
48+
4749
function show(io::IO, ::MIME"text/plain", iter::Union{KeySet,ValueIterator})
4850
isempty(iter) && get(io, :compact, false) && return show(io, iter)
4951
summary(io, iter)

base/some.jl

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ struct Some{T}
1212
value::T
1313
end
1414

15+
Some(::Type{T}) where {T} = Some{Type{T}}(T)
16+
1517
promote_rule(::Type{Some{T}}, ::Type{Some{S}}) where {T, S<:T} = Some{T}
1618

1719
nonnothingtype(::Type{T}) where {T} = Core.Compiler.typesubtract(T, Nothing)

test/operators.jl

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,8 @@ Base.promote_rule(::Type{T19714}, ::Type{Int}) = T19714
133133
@test (FreeMagma(1), FreeMagma(2)) === FreeMagma((1,2))
134134
@test (FreeMagma(1), FreeMagma(2), FreeMagma(3)) === FreeMagma(((1,2), 3))
135135
@test (FreeMagma(1), FreeMagma(2), FreeMagma(3), FreeMagma(4)) === FreeMagma((((1,2), 3), 4))
136+
137+
@test fieldtypes(typeof(Float64 Int)) == (Type{Float64}, Type{Int})
136138
end
137139

138140
@testset "function negation" begin

test/some.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,3 +98,6 @@ using Base: notnothing
9898
# isnothing()
9999
@test !isnothing(1)
100100
@test isnothing(nothing)
101+
102+
# type stability
103+
@test fieldtype(typeof(Some(Int)), 1) === Type{Int}

0 commit comments

Comments
 (0)