[Haskell-beginners] the equivalent of OO class data and methods

Michael P Mossey mpm at alumni.caltech.edu
Thu Apr 2 16:38:27 EDT 2009


Thanks. One question:

Yitzchak Gale wrote:
> 
> One way, which is most similar to the OO approach, is to use
> encapsulation. 

> The other approach is using the class system:
> 
> class Coordinates a where
>   x :: a -> Int
>   y :: a -> Int
> 
> data LayoutItem = LayoutItem { layoutItemX, layoutItemY :: Int }
> 
> instance Coordinates LayoutItem where
>   x = layoutItemX
>   y = layoutItemY
> 
> data Notehead = Notehead { noteheadItemX, noteheadItemY :: Int }
> 
> instance Coordinates Notehead where
>   x = NoteheadX
>   y = NoteheadY
> 

In this case, do local variables still shadow or hide the functions 
contained by the class? In other words, would this work?

foo :: LayoutItem -> Notehead -> Int
foo l n = let y = x l + x n
               z = y l + y n
           in z + y

I'm guessing that the variable y will shadow the function y. This is a 
problem, because I want generic names available for variables.

Now, using encapsulation in modules, I guess it would look like this:

import qualified LayoutItem (x, y)
import LayoutItem ( LayoutItem )
import qualified Notehead (x, y)
import Notehead ( Notehead )

foo :: LayoutItem -> Notehead -> Int

foo l n = let y = LayoutItem.x l + Notehead.x n
               z = LayoutItem.y l + Notehead.y n
           in z + y




More information about the Beginners mailing list