Stream: helpdesk (published)

Topic: ✔ (f::typeof(sin)) vs sin


view this post on Zulip Fons van der Plas (Nov 02 2022 at 13:34):

What is the difference between these two method definitions?

(s::typeof(Base.sin))(x::Vector) = sin.(x)

# versus

Base.sin(x::Vector) = sin.(x)

view this post on Zulip Sukera (Nov 02 2022 at 13:37):

the latter is much more readable, otherwise there shouldn't be any

view this post on Zulip Jakob Nybo Nissen (Nov 02 2022 at 13:37):

Nothing, they lower to the same (except the latter uses Core.Typeof instead of Base.typeof)

view this post on Zulip Notification Bot (Nov 02 2022 at 13:38):

Fons van der Plas has marked this topic as resolved.

view this post on Zulip Mason Protter (Nov 02 2022 at 18:51):

Yeah, defining a function the normal way is actually just syntax sugar for the more general operation of callable structs

view this post on Zulip Mason Protter (Nov 02 2022 at 18:52):

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

view this post on Zulip Expanding Man (Nov 02 2022 at 18:54):

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.

view this post on Zulip Mason Protter (Nov 02 2022 at 18:54):

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: Dec 28 2024 at 04:38 UTC