[Haskell-beginners] How to avoid repeating code

Daniel Fischer daniel.is.fischer at googlemail.com
Tue May 31 10:23:48 CEST 2011


On Monday 30 May 2011 21:44:32, Federico Mastellone wrote:
> I've been looking at the Edison package, it has a big class
> hierarchy without default implementations using functional dependencies
> and I found tidier doing something similar with associated types.

Doesn't surprise me.

> 
> Writing default implementations continues to be troublesome.
> 
> Here is an example adding an elems function to the Collection class
>  elems :: c -> [Elem c]
> I can't write on the MultiMapClass class a default implementation
> for getValueList like this
>  getValueList :: Key m -> m -> [Value m]
>  getValueList k m = elems $ getValues k m
> because elems returns
>  [Elem (Coll m)]
> so I have to write
>  getValueList :: Key m -> m -> [Elem (Coll m)]
> and it doesn't matter that this means the same for the implementations I
> have
>  Elem (Set.Set a) ~ Value (MultiMap k v)
> and
>  Elem IntSet.IntSet ~ Value IntMultiMap

Well, I guess you'd want to have Value m ~ Elem (Coll m) in all cases, so 
you could remove the Value type completely and replace (Value m) with (Elem 
(Coll m)) in all places (although it would be nicer to be able to use the 
shorter Value m, I'm not sure whether you can write such an alias,
type (constraints?) => Value m = Elem (Coll m), be it at the top level or 
in the class declaration, but you could add the equality constraint to the 
class context).

> 
> Now when using classes like this you need to need to think twice when
> coding! Typing becomes much more complicated.
> 
> I don't know if I am too object oriented or is the lack of IDEs but

That could be part of it. Trying to write your code in the OO way in 
Haskell tends to be painful, you have to look at things from a different 
angle to play to the language's strengths.

> reusing code, grouping together code with similarities and managing
> many modules is not easy with Haskell.

Common opinion among Haskellers seems to be that it's easier in Haskell 
than in (most) other languages (massive selection bias, of course).

> Things that I found essential to
> write large programs. I'm starting to think that the easiest way of
> writing generic and reusable code with Haskell is writing a Haskell
> parser and code generator in Haskell.

Considering how easy writing such is in Haskell, that could in fact be not 
too much of an exaggeration :)



More information about the Beginners mailing list