[Haskell-cafe] Non-advanced usage of Type classes

Arnaud Bailly arnaud.oqube at gmail.com
Tue Jun 7 22:16:43 CEST 2011


Hello,
In a recent thread, it has been asserted that defining type class is
something you seldom need when programming in Haskell.

There is one thing that as non-professional Haskell programmer I found
type-classes useful for: Testing. This is probably very OO and is pretty
much influenced by what I read in RWH but I find useful to define TC that
abstract away from low-level interactions with other code, possibly IO
related, in such a way that I can have one implementation for testing and
one implementation for real work that is wired in caller context. This is
what is called "mockist" TDD in some circles: Write code that expresses what
it needs in its own terms, then implement "glue" to the code that provide
the concrete behaviour.

For example, while designing some program (a game...) I defined a type class
thus:

> class (Monad io) => CommandIO io where
>  readCommand  :: io Command
>  writeResult  :: CommandResult -> io ()

Then I defined in a module Commands.IO :

> instance CommandIO IO where
>  readCommand = do input <- getLine
>  ...
> writeResult r         = putStrLn $ show r

and for the purpose of testing I defined in some test module:

> instance CommandIO (S.State ([Command],[CommandResult])) where
>   readCommand   = do ((c:cs),rs) <- S.get
> ....
>   writeResult r = do (cs,rs) <- S.get
> ...

Is this badly designed  code that tries to mimic OO in a functional setting?
If the answer is yes, how could I achieve same result (eg. testing the code
that does command REPL) without defining type classes?

Regards,
Arnaud
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20110607/cdd33788/attachment.htm>


More information about the Haskell-Cafe mailing list