
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

On Thu, Dec 22, 2011 at 14:44, Dennis Raddle
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
test x = maybe (Left "not in map") Right $ M.lookup x testMap
-- brandon s allbery allbery.b@gmail.com wandering unix systems administrator (available) (412) 475-9364 vm/sms

On Thursday 22 December 2011, 20:44:26, Dennis Raddle 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
test = maybe (throwError "not in map") return . flip M.lookup testMap

On Thu, 22 Dec 2011 20:44:26 +0100, Dennis Raddle
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 --
participants (4)
-
Brandon Allbery
-
Daniel Fischer
-
Dennis Raddle
-
Henk-Jan van Tuyl