I have the following function, and it has a type instability (Core.Box
).
In the real code, I use f
as an argument of another function which calls f
multiple times (e.g. bisection to solve f(x)=0
).
How can I make this function type stable?
function test(a)
b = a
if a < 0
b = -a
end
f(x) = x + b
f(10)
end
julia> @code_warntype test(1)
Variables
#self#::Core.Compiler.Const(test, false)
a::Int64
b::Core.Box
f::var"#f#61"
Body::Any
1 ─ (b = Core.Box())
│ Core.NewvarNode(:(f))
│ %3 = a::Int64
│ Core.setfield!(b, :contents, %3)
│ %5 = (a < 0)::Bool
└── goto #3 if not %5
2 ─ %7 = -a::Int64
└── Core.setfield!(b, :contents, %7)
3 ┄ (f = %new(Main.:(var"#f#61"), b))
│ %10 = (f)(10)::Any
└── return %10
6 posts - 4 participants