[Haskell-beginners] figured out use for join!

Dennis Raddle dennis.raddle at gmail.com
Wed Nov 11 21:12:11 UTC 2015

I'm starting to get the hang of certain aspects of typeclasses,
particularly with Maybe and list types. For instance I needed to write a
function as follows:

Ord k => k -> Map k [a] -> Maybe a

which evaluates to "Nothing" if there is no such key in the map, or Just
the first element of [a] if there is such a key, or Nothing if there is
such a key but [a] is null.

So I could write

import qualified Data.Map as M
import Control.Monad
import Data.Maybe

f k m = case M.lookup k m of
  Nothing -> Nothing
  Just xs -> listToMaybe xs

But the case "Nothing -> Nothing" is suspicious... seems like that's always
a clue some typeclass could simplify it. Eventually I figured out

f k = join . fmap listToMaybe . M.lookup k
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20151111/bb392743/attachment-0001.html>

More information about the Beginners mailing list