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?
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With