[Haskell-beginners] use of First or Last
Johann Bach
johann.bach1127 at gmail.com
Mon Jul 26 04:20:56 EDT 2010
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"
More information about the Beginners
mailing list