Created
May 4, 2011 22:33
-
-
Save 23Skidoo/956190 to your computer and use it in GitHub Desktop.
Data.Map.lookup without Maybe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main | |
where | |
import Control.Exception | |
import Data.Map as M | |
import Data.Maybe | |
-- Well, since you don't have any constraints on the type of the input argument, | |
-- you can't be absolutely sure that your function will be always used | |
-- correctly. I too would use an assertion here (or change my function to return | |
-- Maybe if I'm in the mood); another option is to force your clients to check | |
-- that the input is well-formed via the type system: | |
type Key = String | |
type Value = Int | |
type MyMap = M.Map Key Value | |
newtype MapWithAnInterestingElement = Mp MyMap | |
interesting_key :: Key | |
interesting_key = "interesting" | |
makeMapWithAnInterstingElement :: MyMap -> MapWithAnInterestingElement | |
makeMapWithAnInterstingElement m = assert (interesting_key `member` m) (Mp m) | |
getInterestingElement :: MapWithAnInterestingElement -> Value | |
getInterestingElement (Mp m) = fromJust . M.lookup interesting_key $ m | |
-- I admit that this solution doesn't scale. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment