Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to place haskell field names in different name spaces?

Tags:

haskell

Consider the following two types:

data Point=Point{x::Float,y::Float}
data Rectangle = {upperLeft::Point, bottomRight::Point}
data Square = {upperLeft::Point, bottomRight::Point}

the ghc compiler complains that the upperLeft field name in Rectangle conflicts with that of Square. This seems strange as on the face of it each field name should be in the namespace of the type, otherwise one cannot reuse field names, and I suspect that would be a common enough expectation.

For example to define a variable we write:

let a=Rectangle{upperLeft=Point 2 3, bottomRight=Point 7 7}
let a=Square{upperLeft=Point 2 3, bottomRight=Point 7 7}

From this we can see that we ought to be able to expect that each field name should be within their respective type namespace.

Is my usage correct or are my expectations wrong? Is there someway to fix this?

like image 660
Mozibur Ullah Avatar asked Jan 09 '13 22:01

Mozibur Ullah


Video Answer


1 Answers

Since objects can be accessed through their field names, the compiler must be able to infer an object's type from its field name. For instance, in

boundingBox x = bottomRight x - upperLeft x

the accessors bottomRight and upperLeft are used to infer the type of x. If multiple types were allowed to have the same accessor name, then it wouldn't be possible to infer the type.

To avoid name collisions, a common convention is to put a prefix on all field names. This convention is used in the GHC project.

data Rectangle = {rc_upperLeft :: Point, rc_bottomRight :: Point}
data Square =    {sq_upperLeft :: Point, sq_bottomRight :: Point}
like image 64
Heatsink Avatar answered Sep 25 '22 15:09

Heatsink