What is the difference between these two method definitions?
(s::typeof(Base.sin))(x::Vector) = sin.(x)
# versus
Base.sin(x::Vector) = sin.(x)
the latter is much more readable, otherwise there shouldn't be any
Nothing, they lower to the same (except the latter uses Core.Typeof
instead of Base.typeof
)
Fons van der Plas has marked this topic as resolved.
Yeah, defining a function the normal way is actually just syntax sugar for the more general operation of callable structs
e.g. writing
f(x) = y
is just special syntax to avoid writing something like
struct typeof_f end
const f = typeof_f
(f::typeof_f)(x) = y
Of course it should go without saying that you should NOT actually define Base.sin(x::Vector) = sin.(x)
as it's extremely confusing, and type piracy that will lead to god knows what shenanigans down the road.
One practical difference though is that for the first thing you wrote @Fons van der Plas, you don't actually have to write the Base.
part. Using this syntax lets you define methods on external functions without import
or qualifying their name
Last updated: Nov 06 2024 at 04:40 UTC