[Haskell-cafe] nested maybes

Mattias Bengtsson moonlite at dtek.chalmers.se
Sun Feb 4 10:41:08 EST 2007


On Sun, 2007-02-04 at 19:54 +0530, Martin DeMello wrote:
> I have a Data.Map.Map String -> (Layout, [String]) as follows:
> 
> type Anagrams = [String]
> type Cell = (Layout, Anagrams)
> type WordMap = Map.Map String Cell
> 
> exists str wmap =
>   let a = Map.lookup (sort str) wmap in
>       case a of
>            Nothing -> False
>            Just x -> case (find (== str) (snd x)) of
>                           Nothing -> False
>                           _       -> True
> 
> the existence test looks ugly - any more compact way to write it?
> 

Using the Maybe Monad is one solution i think (as in: i _think_ this
should work):

findIt str wmap = do 
  a <- Map.lookup (sort str) wmap
  return $ find (== str) (snd a)

exists str wmap = 
  case findIt str wmap of
    Nothing -> False
    Just _ -> True

The Maybe monad is very nice for abstracting away all those
case-expressions.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part
Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070204/3780a9ef/attachment-0001.bin


More information about the Haskell-Cafe mailing list