Some questions about function (size(i::Int))

I saw a function as follows. Can you tell me what’s the mean of size(i::Int)=i ==0 ? 3 : 4*i ?

function t3(input)
    vect=[]
    size(i::Int)=i ==0 ? 3 : 4*i
    for i in 1: (input)
        append!(vect, size(i))
    end
    return vect
end

t3(5)

It’s a local function definition. It’s the same as

function size(i::Int)
    return i==0 ? 3 : 4*i
end

Tangential, but because I’ve come across something similar recently: wouldn’t it be better to write

size(i::Int) = ...

function t3(input)
    ... append!(vect, size(i))
end

i.e. define size outside of t3? Otherwise the function would be re-defined every time t3 is called, although I’m not sure this makes a difference in practice?

(and for OP: this is a very convoluted way of writing t3(input) = [i == 0 ? 3 : 4i for i ∈ 1:input] - you are working on an Vector{Any} when initialising things with [] which is terrible for performance)

Thank you for you immediately reply. I have known it.
Local functions like this cost me a lot of time, are there some documents about this?

Thank you again for your help.

Thank you for your advice.
I tried your first type, it tell me UndefVarError: i not defined
Your second way is OK, it works well.

Sorry,nilshg. I have known your mean, thank you very much.

1 Like

This isn’t how closures work. They get defined once per source code definition, not every time they are “executed”.

2 Likes