[Haskell-cafe] "data" and classes question

Bulat Ziganshin bulat.ziganshin at gmail.com
Tue Jan 29 11:52:32 EST 2008

Hello Chaim,

Tuesday, January 29, 2008, 7:26:25 PM, you wrote:

your approach is completely wrong (OOP-inspired, but haskell isn't OOP
language). type class is common interface to different types. just for

data BinState = On | Off
data BinChange = OnToOff | OffToOn

class MinValue a where
  minvalue :: a
instance MinValue BinState where
  minvalue = On
instance MinValue BinChange where
  minvalue = OnToOff

here we define class with a function (class without functions hardly
can be used for anything useful) and provide implementation of this
function for different types. then, we can use it in any code:

main = print (minValue :: BinChange)

and in particular we can declare derived class. the advantage of
derived class is that it can use all functions of base class. but it
should add its own functions too, otherwise it will be again useless:

class (MinValue a) => BoundedValue a where
  maxvalue :: a
instance MinValue BinState where
  maxvalue = Off
instance MinValue BinChange where
  maxvalue = OffToOn

now, for values in BoundedValue class you can use both functions.
also, you can use functions from MinValue class in default
definitions of BoundedValue functions

but if you just need to use functions from MinValue class, you don't
need to declare one more class

type classes can be compared with Java interfaces. they aren't 100%
equal, though. read http://haskell.org/haskellwiki/OOP_vs_type_classes
and especially its "further reading" section

Best regards,
 Bulat                            mailto:Bulat.Ziganshin at gmail.com

More information about the Haskell-Cafe mailing list