Counting all subtypes

I’m trying to count all subtypes of given type (subtypes of these subtypes and so on) with a recursive function, but for now I only managed to write one showing the structure by creating arrays in arrays…

function allSubtypes(T::Type)
    if length(subtypes(T)) > 0
        return allSubtypes.(subtypes(T))
    else
        return T
    end
end

Something like this?

julia> function countsubtypes(T::Type; recursive=false)
           _subtypes = subtypes(T)
           n = length(_subtypes)
           if !recursive
               return n
           end
           n + sum(countsubtypes(_T) for _T in _subtypes)
       end
countsubtypes (generic function with 1 method)

julia> countsubtypes(Integer; recursive=true)
14

julia> countsubtypes(Integer; recursive=false)
3

julia> countsubtypes(Signed; recursive=false)
6

julia> countsubtypes(Signed; recursive=true)
6
1 Like

Yes! But I think that the output for some types will be incorrect, for example Number gives 7.

Feel free to debug it ; ) I can have a look later, currently in a video conference…

2 Likes

Sure! Thank you for help, I’ll try my best. Have a nice conference :slight_smile:

You have to make the call of the countsubtypes function in the sum recursive to walk the full subtype tree.

function countsubtypes(T::Type; recursive=false)
           _subtypes = subtypes(T)
           @show _subtypes
           n = length(_subtypes)
           if !recursive || n == 0
               return n
           end
           n + sum(countsubtypes(_T, recursive=true) for _T in _subtypes)
       end
2 Likes

Exactly, thanks :))