
I am reading "typeclassopedia" and got curious about how the monoid instances First or Last could be applied to a real problem. Any suggestions for improvement would be welcome. So I imagined this problem: We have a list of executives in a company, and their rank. Some executives have assistants, some don't. import Data.List import Data.Monoid import Data.Function data Executive = Executive { name :: String , rank :: Int , assistant :: Maybe String } deriving (Show) We want to bring an urgent matter to an executive. We'd like to contact the highest ranking executive, but we also don't want to disturb any executive directly, so we want to contact the highest ranking executive with an assistant. This function finds the name of that assistant: findContact :: [Executive] -> Maybe String findContact = getLast . mconcat . map (Last . assistant) . sortBy (compare `on` rank) data1 = [ Executive "Mary Poppins" 1 Nothing , Executive "Fred Flinstone" 2 (Just "John Deere") , Executive "Ann Curry" 3 (Just "Terry Crews") ]
findContact data1 Just "Terry Crews"

Hi Johann,
On Mon, Jul 26, 2010 at 10:20 AM, Johann Bach
I am reading "typeclassopedia" and got curious about how the monoid instances First or Last could be applied to a real problem. Any suggestions for improvement would be welcome.
The code looks fine to me. The Last monoid is useful when parsing command line flags and you want the last mention of a flag to have precedence. You can further extend this to allow for default values of flags and flag definitions in config files. See Duncan's explanation of how this is used in Cabal: http://www.mail-archive.com/cabal-devel@haskell.org/msg01492.html Cheers, Johan
participants (2)
-
Johan Tibell
-
Johann Bach