How to make a function defined from getindex type safe?

testv = [1,2,3,4,5]
testf(n) = testv[n+1]
@code_warntype testf(4)

This gives me

  #self#::Core.Compiler.Const(testf, false)

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

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