Help understanding an anonymous function

I am reviewing someone else’s code and came across this anonymous functions. Could you please help me understand: (1) when it is executed and how it is called, and (2) the syntax why there is “(token)” the second type passed in separate pair of parenthesis. I would have expected “function(m::Int64, token)”

function(m::Int64) (token)


return a, b
end

The code exactly as you typed should not work (extra space) and what you are seeing is most likely not an anonymous function. I don’t know where you get that code from but you are most likely seeing (d::Int)(x::Int) = d + x?

1 Like

That looks like a callable object, not a closure (anonymous function).

2 Likes

This is an exact cut and paste from JuliaCon2020 presentation, the url is https://github.com/Ayushk4/JuliaCon20_Talk/blob/master/Sentiment.ipynb
(the code is a stand alone, 4th block).

My question is more about how this function is defined and executed.

function (m::SentimentModel)(token_onehot)
Flux.reset!(m.lstm1)
Flux.reset!(m.lstm2)
embed(x) = m.W_Embed * x’
e = embed.(token_onehot)
w = @. m.lstm2(m.lstm1(e))
logits = m.d(m.lstm2.state[1]) # We just need the last hidden state of the LSTM
return Flux.softmax(logits), logits
end

Thank you for the direction. It is a FUNCTION-LIKE-OBJECT. More info here:
https://docs.julialang.org/en/v1/manual/methods/#Function-like-objects

1 Like

FYI. I found the answer. It is function-like-object. Methods · The Julia Language