[Haskell-beginners] How to avoid repeating code

Federico Mastellone fmaste at gmail.com
Thu May 26 02:23:06 CEST 2011


Hi,

I created a Data.MultiMap module based on Data.Map and Data.Set like this:

data MultiMap k v = MultiMap (Map k (Set v))

and a Data.IntMultiMap module based on Data.IntMap and data.IntSet like
this:

data IntMultiMap = IntMultiMap (IntMap IntSet)

For example the functions to add a value I wrote are:

For MultiMap:
addValue :: k -> v -> MultiMap k v -> MultiMap k v
addValue k v (MultiMap m) = MultiMap $ Map.insertWith (\new old ->
Set.insert v old) k (Set.singleton v) m

For IntMultiMap:
addValue :: Int -> Int -> IntMultiMap -> IntMultiMap
addValue k v (IntMultiMap m) = IntMultiMap $ IntMap.insertWith (\new old ->
IntSet.insert v old) k (IntSet.singleton v) m

Both modules look almost the same, with the same
documentation, same behavior, same function names but with different type
signatures.

Is there a way to make this simpler?

The same thing happens to the modules that are using MultiMap and
IntMultiMap, I have to write two versions of each.

Thanks!

-- 
Federico Mastellone
Computer Science Engineer - ITBA

".. there are two ways of constructing a software design: One way is to make
it so simple that there are obviously no deficiencies, and the other way is
to make it so complicated that there are no obvious deficiencies. The first
method is far more difficult."

Tony Hoare, 1980 ACM Turing Award Lecture.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20110525/67e83a62/attachment.htm>


More information about the Beginners mailing list