[Haskell-beginners] the equivalent of OO class data and methods
Michael Mossey
mpm at alumni.caltech.edu
Thu Apr 2 08:08:31 EDT 2009
I'm making the transition from OO to Haskell, and a major problem for me is that I'm
used to OO, where member variables are distinct from other variables and functions,
so I can use totally generic member variable names and never have a conflict with
other member variables or local variables.
For example, if I want to create LayoutItem and name its coordinates x and y, I do this:
(Python)
class LayoutItem :
def __init__( self, x, y ) :
self.x, self.y = (x, y )
Then later,
p = LayoutItem( 10, 20 )
Then later I can refer to p.x and p.y.
I can also create other classes and name *their* member variables x and y, with no
confusion.
Now, I know that in Haskell I can do
data LayoutItem = LayoutItem { x, y :: Int }
Later,
let p = LayoutItem { x = 10, y = 20 }
I have read that this automatically creates "accessor" functions called x and y, so I
can refer to (x p) and (y p)
let foo = (x p)^2 + (y p)^2
Now let's say I create another type that also uses x and y:
data Notehead = Notehead { x, y :: Int }
n = Notehead { x = 100, y = 200 }
This doesn't work. Apparently the accessor functions x and y (for LayoutItem) have
global scope and conflict with those for Notehead.
Which means I have to name them different things, which is awkward. For example,
data LayoutItem = LayoutItem { layoutItemX, layoutItemY :: Int }
data Notehead = Notehead { noteheadItemX, noteheadItemY :: Int }
Also, I tried using some of these accessor function names as variables, and the
compiler doesn't distinguish between them. For example,
myfunc :: Notehead -> LayoutItem -> Int
myfunc n p = let layoutItemY = layoutItemX p
z = layoutItemY n
in z^2
This doesn't work, because declaring layoutItemY as a variable hides its defintion as
an accessor function.
Is there a way to get what I want from Haskell?
Thanks,
Mike
More information about the Beginners
mailing list