How can I generalize the function of calling a user type to an abstract type?

I have the following mock setup with an abstract type, concrete types as subtypes, and a function f that takes two arguments, the first of which is Letter .

 abstract type Letter end struct A <: Letter end struct B <: Letter end f(::A, x) = ('a', x) f(::B, x) = ('b', x) a = A() b = B() 

I would like to define a custom call function for the Letter subtypes that just calls f .

 (t::A)(x) = f(t, x) (t::B)(x) = f(t, x) 

While this works, it seems redundant, especially considering that there can be many subtypes of Letter . My attempts are as follows, but it does not seem to work.

 julia> (t::Letter)(x) = f(t, x) ERROR: cannot add methods to an abstract type julia> (t::T)(x) where T <: Letter = f(t, x) ERROR: function type in method definition is not a type 

How can I generalize the call function to match any (specific) subtype of Letter ?

+5
source share

Source: https://habr.com/ru/post/1268917/


All Articles