Cale Gibbard wrote:
Unifying these two under a single operation is certainly trickier,
and it's a little more questionable that it should be done at all,
given that their types are so different -- below is the closest I
could come to it off-hand.
---
{-# OPTIONS_GHC -fglasgow-exts #-} -- for fundeps/multiparameter
classes import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
class Insert t c a | c a -> t where
insert :: t -> c a -> c a
instance (Ord a) => Insert a Set a where
insert x s = Set.insert x s
instance (Ord k) => Insert (k,a) (Map k) a where
insert (k,v) m = Map.insert k v m
exampleSet = insert 5 $ insert 6 $ Set.empty
exampleMap = insert (1,2) $ insert (2,7) $ Map.empty
----
Perhaps someone else will have some ideas as to suitable typeclass
magic to allow for the curried form rather than using tuples.
- Cale
Oh, this is a little less general, but simpler to use:
{-# OPTIONS_GHC -fglasgow-exts #-}
import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
class Insert t c | c -> t where
insert :: t -> c -> c
instance (Ord a) => Insert a (Set a) where
insert x s = Set.insert x s
instance (Ord k) => Insert (k,a) (Map k a) where
insert (k,v) m = Map.insert k v m
exampleSet = insert 5 $ insert 6 $ Set.empty
exampleMap = insert (1,2) $ insert (2,7) $ Map.empty
Thanks! I'm impressed. Obviously there is a lot more power in type classes
than I'd thought. I hadn't realised that you could separate the Ord a and
Ord k from the type signature in the class declaration, and put them in
instance declarations like that (for example).
It would be really interesting to see how far one could go in factoring all
the collection type functions/values into type classes.
Best regards,
Brian.
_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe