Thank you very much Karsten for the link to foldM ! Thank them for understanding this answer.
So, if we use foldM , we can write a function that repeatedly executes a lookup chain encoded through several directories that depend on each previous result. If, thanks to the use of monads , at any point in the lookup current key cannot be found in the directory, it will end and return Nothing :
lookupALot :: Eq a => a -> [(a,b)] -> Maybe b lookupALot key directories = foldM lookup key directories
it takes the form of a form
foldM f k1 [d1, d2, ..., dm] -- k == key, d == directory == do k2 <- f k1 d1 k3 <- f k2 d2 ... f km dm
which is the same structure as
do number <- lookup name phonebook registration <- lookup number governmentDatabase lookup registration taxDatabase
Therefore, a more compact way to write getTaxOwed would be:
getTaxOwed :: String -> Maybe Double getTaxOwed name = foldM lookup name [phonebook, governmentDatabase, taxDatabase]
What a view it takes me! This line of code will find the phone number associated with the person name , then check the governmentDatabase with their number on their registration and finally find your tax information from this registration . Note that this will only work for data in the form [(a,b)] , as indicated by the lookupALot type.