[Haskell-beginners] When a return type constrained by class

Brandon Allbery allbery.b at gmail.com
Sun Mar 18 10:00:46 CET 2012


On Sun, Mar 18, 2012 at 02:23, Haisheng Wu <freizl at gmail.com> wrote:

> Hi there,
>  Do you have any idea why the following code is not valid?
>
> class Guess g where
>  makeGuess :: g -> String
>
> instance Guess GuessLetter where
>  makeGuess = ...
>
> instance Guess GuessWord where
>  makeGuess = ...
>
> *-- | This function is nod valid *
> nextGuess :: Guess g => String -> g
> nextGuess = ...
>

You are probably assuming that you get to decide within nextGuess what type
it will return; in fact, the type it will return is set by its context when
invoked, and your implementation must be prepared to return any Guess based
on what the caller wants.  Since nextGuess has no way to *get* at that
context, and the typeclass has no method that can be used to produce a
result based on the requested result type (as with e.g. Read), it's not
clear to me that it can actually return anything (that is, the only
possible result is _|_).

Mantra:  "Typeclasses are not OOP."  Don't try to think of them as OOP, you
will only get into trouble.

-- 
brandon s allbery                                      allbery.b at gmail.com
wandering unix systems administrator (available)     (412) 475-9364 vm/sms
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20120318/e4474e5d/attachment.htm>


More information about the Beginners mailing list