[Haskell-cafe] Haskell record extension?

Andrew Coppin andrewcoppin at btinternet.com
Fri Jun 15 17:38:35 EDT 2007

bf3 at telenet.be wrote:
> I'm learning Haskell. 
> I was surprised that the following example did not compile:
> data Vector2 = Vector2 { x :: Float, y :: Float }
> data Vector3 = Vector3 { x :: Float, y :: Float, z :: Float }
> error: "Multiple declarations of `Main.x'"
> This seems to be a known issue and if I understand it correctly it has to do
> with the fact that Haskell does not support function general overloading ala
> C++. One either has to use type classes, or put each record in a separate
> module and fiddle with the qualified namespaces.
> I read multiple papers with proposals to fix this, but does GHC implement
> any of these?

AFAIK, GHC doesn't implement any fix for this. (I've been wrong before 

One easy workaround is to simply do

data Vector2 = Vector2 { x2, y2 :: Float }
data Vector3 = Vector3 { x3, y3, z3 :: Float}

Another (which is usually a bad idea) is

data Vector = Vector2 { x, y :: Float} | Vector3 { x, y, z :: Float}

Usually you'll want to be able to seperate Vector2 functions from 
Vector3 functions, which the above won't allow you to do.

And the other possibility is to play with type classes - something like

class V1 v where
  x :: v -> Float

instance V1 Vector2 where
  x (Vector2 f0 f1) = f0

and so on.

And the final possibility is multiple modules and play with namespaces 
that way - but that's probably overkill.

More information about the Haskell-Cafe mailing list