[Haskell-beginners] error monad and Map lookup

Henk-Jan van Tuyl hjgtuyl at chello.nl
Thu Dec 22 22:06:16 CET 2011


On Thu, 22 Dec 2011 20:44:26 +0100, Dennis Raddle  
<dennis.raddle at gmail.com> wrote:

> Is there a more elegant way to write 'test' in the following?
>
> import qualified Data.Map as M
> import Data.Map(Map)
> import Control.Monad.Error
>
> testMap :: Map Int String
> testMap = M.fromList [(1, "whatever"), (2, "dude")]
>
> test :: Int -> Either String String
> test x = do
>   y <- case M.lookup x testMap of
>          Nothing -> throwError "not in map"
>          Just z -> return z
>   return y

If you run hlint (available on Hackage), you get the following message:

   MonadicCase.hs:11:10: Error: Redundant return
   Found:
     do y <- case M.lookup x testMap of
                 Nothing -> throwError "not in map"
                 Just z -> return z
        return y
   Why not:
     do case M.lookup x testMap of
            Nothing -> throwError "not in map"
            Just z -> return z


And of course, you can leave out the 'do'; the test function then becomes:
   test x =
     case M.lookup x testMap of
       Nothing -> throwError "not in map"
       Just z  -> return z


Regards,
Henk-Jan van Tuyl


-- 
http://Van.Tuyl.eu/
http://members.chello.nl/hjgtuyl/tourdemonad.html
Haskell programming
--



More information about the Beginners mailing list