[Haskell-cafe] The (!) operation

Francesco Mazzoli f at mazzo.li
Thu Mar 8 17:53:04 CET 2012


On 08/03/12 16:19, Christopher Done wrote:
> ‘Ello.
>
> Is there a generalization of this operator? It's all over the place,
> it's basically
>
>      (!) :: (Monad m, Indexed collection index value) =>  index ->
> container ->  m value
>
> We have `(!!)` on lists, `(!)` on maps, vectors, json objects, …
> (doesn't seem there's one for bytestring)
>
> (Though I seem to recall the monadic return value being frowned upon
> but I don't recall why.)
>
> Thoughts?
>
> Ciao!
>

Ciao!

It doesn't exist as far as I know, but a "Map" typeclass can be easily 
envisioned, e.g.:

{-# LANGUAGE MultiParamTypeClasses
            , FunctionalDependencies
            , FlexibleInstances
   #-}
module MapClass (MapClass(..)) where

import Data.Map (Map)
import qualified Data.Map as Map
import Data.Hashable (Hashable)
import Data.HashMap.Lazy (HashMap)
import qualified Data.HashMap.Lazy as HashMap

import qualified Data.List as List

class MapClass m k v | m -> k, m -> v where
     empty  :: m
     lookup :: k -> m -> Maybe v
     insert :: k -> v -> m -> m

instance Ord k => MapClass [(k, v)] k v where
     empty      = []
     lookup     = List.lookup
     insert k v = ((k, v) :)

instance Ord k => MapClass (Map k v) k v where
     empty  = Map.empty
     lookup = Map.lookup
     insert = Map.insert

instance (Hashable k, Eq k) => MapClass (HashMap k v) k v where
     empty  = HashMap.empty
     lookup = HashMap.lookup
     insert = HashMap.insert



More information about the Haskell-Cafe mailing list