Dispatch on lambda functions

Hi, is there a way to dispatch on lambda functions? It seems that lambda’s don’t have a specific type for themselves (unlike Functions), but are rather uniquely typed with a counter (var"#29#30"). I would like to dispatch like in the following MWE (or at least to be able to reference var"..." types):

λ = () -> 2  # typeof(λ) == var"#29#30"
x = 2

fun(x) = x
fun(x::Lambda) = x()

fun(x)  # == 2
fun(λ)  # == 2

Thanks in advance

julia> fun(x::typeof(λ)) = x()
fun (generic function with 2 methods)

julia> fun(λ)

thanks for your answer, I should have made clearer that I want to dispatch on the fact that the input is any lambda function, not only this particular one

Lambdas are not special - they’re regular <: Functions (implemented as callable structs that subtype Function). They just don’t have a convenient name, but rather a generated one.

great, thanks, I didn’t know lambdas were <: Function !

Note that this doesn’t allow you to distinguish lambdas from named functions:

julia> typeof(+) <: Function

Function is an abstract type after all and every function in julia has its own type, that’s <: Function itself.

1 Like