I have a dictionary of tuples. Inside one of those tuples is one thing I care about. What’s the best way to find that one thing? How can I make it fast? I feel like I have some things to learn about associative collections.
Here’s a mockup of my code, where I have a dictionary of pet owners and their pets. I know there’s one and only one Cat, and I’d like to find that cat. I have some code to do it, but it feels really bulky compared to the rest of my code.
abstract type Pet end struct Dog <: Pet; name::String; end struct Cat <: Pet; name::String; end struct Ox <: Pet; name::String; end # Create an example dictionary. pets = Dict("Cindy" => (Dog("Fido"), Cat("Captain Snuggly Pants")), "Tom" => (Ox("Socks"), Dog("Chewbacca"))) # Find the cat. cat = Cat("empty cat") # Defined so that cat has global scope. for these_pets in values(pets) # Get tuple of pets for each entry. cats = filter(e -> isa(e, Cat), these_pets) # Look for a Cat. if !isempty(cats) # If we found one, accept it and break. cat = first(cats) break end end
I can definitely make the code shorter by
vcating all of those tuples together into a literal collection and then calling
first(filter(p -> isa(p, Cat), ...)) on it, but that seems hugely wasteful. Time is critical here; there will be many pet owners and many pets, the whole thing will need to run many times on different collections, and who wouldn’t want to find Captain Snuggly Pants as soon as possible?