Skip to content

Instantly share code, notes, and snippets.

@vlas-ilya
Created October 15, 2015 10:35
Show Gist options
  • Save vlas-ilya/faa380f913b05c2b452d to your computer and use it in GitHub Desktop.
Save vlas-ilya/faa380f913b05c2b452d to your computer and use it in GitHub Desktop.
import Prelude hiding (lookup)
import qualified Data.List as L
class MapLike m where
empty :: m k v
lookup :: Ord k => k -> m k v -> Maybe v
insert :: Ord k => k -> v -> m k v -> m k v
delete :: Ord k => k -> m k v -> m k v
fromList :: Ord k => [(k,v)] -> m k v
fromList [] = empty
fromList ((k,v):xs) = insert k v (fromList xs)
newtype ListMap k v = ListMap { getListMap :: [(k,v)] }
deriving (Eq, Show)
instance MapLike ListMap where
empty = ListMap []
lookup k (ListMap m)
| k `elem` (map fst m) = Just $ snd $ head $ filter (\(k', v') -> k == k') m
| otherwise = Nothing
insert k v (ListMap m)
| k `elem` (map fst m) = ListMap $ map (\p@(k', v') -> if k' == k then (k', v) else p) m
| otherwise = ListMap $ (k, v):m
delete k (ListMap m) = ListMap (filter (\(k', _) -> k /= k') m)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment