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

Yves Parès limestrael at gmail.com
Wed Jun 8 00:24:37 CEST 2011


> 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?

Why would that be badly designed? And why would that be more OO? IMO it is a
perfectly suited usage of type classes.

> Here's how I do it:

> data InteractiveState = InteractiveState {
>  state_read :: IO Command
> , state_write :: Result -> IO ()
> }

Well, it's pretty much the same thing, except you explicitely carry a value
containing your methods instead of simply carrying a type. Plus it delays
the resolution of which function will be called to the execution.
With typeclasses, it will be determined statically, no need to carry the
functions.


2011/6/7 Arnaud Bailly <arnaud.oqube at gmail.com>

> 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
>
>
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20110608/98605503/attachment.htm>


More information about the Haskell-Cafe mailing list