Type design question

Graham Klyne GK@ninebynine.org
Mon, 28 Jul 2003 17:21:21 +0100


At 15:40 28/07/03 +0200, Konrad Hinsen wrote:
> > This is beginning to get a little ugly, but I think that's largely
> > because you're using type classes in too much of an OO style (this is
>
>I am coming from OO indeed...

Me too.

Twice now I have used Haskell classes in a way suggested by an OO 
programming background, and have later ended up replacing the class by a 
'data' containing functions.

Here's a point to consider:  suppose you want to have a list of "class" 
instances:  if you use the "class" mechanism, then every member of the list 
must be a member of the same instance type of the class, which is not what 
is usually required for OO programming.

An alternative is to define something like:

 > data MyInterface = MyInterface
 >     { method1 :: Int  -> String -> Blob
 >     , method2 :: Bool -> String -> Blob
 >     , method3 :: Blob -> String
 >     }

then if you have:

 > anObj :: MyInterface

and write functions like

 > foo = method1 anObj 5 "hello"
 > bar = method3 anObj foo

etc.

In creating instances of MyInterface, the higher order function features of 
Haskell, and currying, are most useful.  Functions that return values of 
type MyInterface take on the role of OO class constructors (or kit classes).

(The above code completely unchecked, but I hope it illustrates an approach.)

#g


-------------------
Graham Klyne
<GK@NineByNine.org>
PGP: 0FAA 69FF C083 000B A2E9  A131 01B9 1C7A DBCA CB5E