Hi Rob,
I usually prefer type class approach for early stage of development.
Type class approach is more flexible, less works required.
One might get a function with lots of constraints, and quite a lot of
language extensions may appear, though it works.
Once things got settled down, I reconsider API.
The type signatures shown in your example::
class FooC a where
mkFooC :: IO a
readFooC :: a -> IO Int
incrFooC :: a -> IO ()
and:
data FooT a = FooT {
readFooT :: IO a
, incrFooT :: IO ()
}
Resulting type of 'readFooC' is fixed to 'Int' within the type class.
On the other hand, resulting type of 'readFooT' is type variable 'a'.
Made slight modification to the type class shown in your
example. Changed result type of 'readFooC' to take associated
type:
http://hpaste.org/83507Once criteria for comparison I can think is performance.
For compilation time, I guess functional object approach give better
performance, since some of the works done by compiler are already done
manually. Though, I haven't done benchmark of compilation time, and
not sure how much interest exist in performance of compilation.
For runtime performance, one can do benchmark in its concrete usecase.
I suppose, generally, functions defined with type class are slower
than functions having concrete type. See SPECIALIZE pragam in GHC[1].
Another criteria I can think is extensibility.
Suppose that we want to have new member function, 'incrTwice'. If we
have chance to change the source of 'FooC', adding new member function
to 'FooC' type class directly is possible, with default function body
filled in.
class FooC a where
type FooCVal a :: *
mkFooC :: IO a
readFooC :: a -> IO (FooCVal a)
incrFooC :: a -> IO ()
incrTwiceC :: a -> IO ()
incrTwiceC a = incrFooC a >> incrFooC a
Though, having reasonable default is not always possible.
For additional source of inspiration, might worth looking the
classic[2], and "scrap your type classes" article[3].
[1]:
http://www.haskell.org/ghc/docs/7.6.1/html/users_guide/pragmas.html#specialize-pragma
[2]:
http://homepages.inf.ed.ac.uk/wadler/papers/class/class.ps[3]:
http://www.haskellforall.com/2012/05/scrap-your-type-classes.html
Hope these help.
Regards,
--
Atsuro