Why is it apparently not possible to capture a DataType
inside a closure in a typestable manner? Consider
function create_closure1(data)
bufT = eltype(data)
(i) -> begin
buf = Vector{bufT}(undef,1)
buf[1] = data[i]
end
end
closure = create_closure1(data)
@code_warntype closure(1) # type could be infered
however if i capture the data
itself eltype(data)
inside the closure works fine
function create_closure2(data)
(i) -> begin
buf = Vector{eltype(data)}(undef,1)
buf[1] = data[i]
end
end
closure = create_closure2(data)
@code_warntype closure(1) # type could be infered
In reality my problem is a bit more complicated because the buffer type is conditional. I solved the problem for now by creating an empy container of that type rather than using bufT
in the clousre directly but this somehow feels hacky.
function conditional_example(data, hasmissing)
bufT = hasmissing ? Union{Missing, eltype(data)} : eltype(data)
buf_prototype = Vector{bufT}(undef,0)
(i) -> begin
buf = Vector{eltype(buf_prototype)}(undef,1)
buf[1] = data[i]
end
end
closure = conditional_example(data, true)
@code_warntype closure(1) # type could be infered
Any insights on that? Is it a bug? Or am I just missing something? I’ve played around with quite a lot of variations using let
blocks before finding the stupid buf_prototype
solution…