[Haskell-cafe] Trouble with record syntax and classes
Aaron McDaid
aaron at aaronmcdaid.com
Mon Feb 26 17:27:23 EST 2007
On 2/26/07, Thomas Nelson <thn at cs.utexas.edu> wrote:
> I'm brand new to haskell and I'm having trouble using classes. The basic idea
> is I want two classes, Sine and MetaSine, that are both instances of ISine.
'class' in Haskell doesn't mean the same as 'class' in C++ or Java. I
found it easier at first to thing of them as:
A Haskell 'class' is more like a Java interface.
Haskell types are more like what you might think of as 'class'es.
Haskell 'instance' means Java 'implement'
There is no word that means that same as 'instance' from Java/C++
terminology. I suppose we would call them 'values' or something.
Somebody more knowledgeable can describe the etymology of the terms,
but these 3 observations should help.
> data Sine =
> Sine { period :: Integer, offset :: Integer, threshold :: Integer, letter :: String}
>
> instance Sine ISine where
> act time (Sine self)
> |on time self = [letter self]
> |otherwise = []
To be honest, I'm not sure what you're trying to do here, so beware of
my advice...
You might want to do this instead:
data Sine = Sine Integer Integer Integer String
instance ISine Sine where -- note that ISine should come before Sine
period (Sine p _ _ _ _) = p
period (Sine _ o _ _ _) = o
-- and so on ...
There can only be a single function called period, which will take a
thing of any type which is an instance of ISine and return an Integer.
So every time you tell Haskell "this type is to be an implementation
of ISine" you have to write the period function for it as I have done
for Sine here.
> -Thomas
Aaron
More information about the Haskell-Cafe
mailing list