Skip to content

Instantly share code, notes, and snippets.

@23Skidoo
Created May 4, 2011 22:33
Show Gist options
  • Save 23Skidoo/956190 to your computer and use it in GitHub Desktop.
Save 23Skidoo/956190 to your computer and use it in GitHub Desktop.
Data.Map.lookup without Maybe
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