zwwi
1
testv = [1,2,3,4,5]
testf(n) = testv[n+1]
@code_warntype testf(4)
This gives me
Variables
#self#::Core.Compiler.Const(testf, false)
n::Int64
Body::Any
1 ─ %1 = (n + 1)::Int64
│ %2 = Base.getindex(Main.testv, %1)::Any
└── return %2
How can I define such a function in a type-safe way?
You are accessing a global variable whose type may change. Pass testv as an argument to the function instead.
1 Like
zwwi
3
Thanks a lot! I figured it out later on the goal can also be achieved by making testv const
.
Here I get another one:
test(x) = x>0 ? 1.0 : 1im
How to make this one type safe without annotating it as Complex64? That is, I want Float64 for positive argument and Complex{Float64} otherwise.
That’s just not going to be type stable. The closest you could do is return 1.0+0im
1 Like