Finding the number of arguments of an anonymous function

FWIW, applicable seems to fare fairly well and should be safe:

julia> a(f) = applicable(f, 1) ? f(1) : f(1,2);

julia> t(f) = try; f(1); catch; f(1,2); end;

julia> m(f) = first(methods(h)).nargs == 1 ? f(1) : f(1,2);

julia> @btime a($h)
  156.568 ns (0 allocations: 0 bytes)
3

julia> @btime t($h)
  6.479 μs (2 allocations: 48 bytes)
3

julia> @btime m($h)
  3.611 μs (14 allocations: 784 bytes)
3
6 Likes