[Haskell-beginners] When a return type constrained by class
orclev at gmail.com
Sun Mar 18 10:13:10 CET 2012
I'd guess the problem is because nextGuess isn't capable of producing any
instance of Guess. The type signature of a function isn't just to provide
callers information about a function like in most languages, it's also a
contract the function itself must abide by. In contrast it's common in an
OO language like Java to provide a more general return type like an
interface or superclass in the method declaration, and then to return a
more concrete type in the actual method. Haskell in contrast requires that
you be capable of returning *anything* that your functions type signature
claims it can. In your example, nextGuess must be capable of producing
*any* instance of nextGuess that a caller of the function requests. Put
another way, both of these must be valid:
nextGuess "example" :: GuessLetter
nextGuess "example" :: GuessWord
Typically this is accomplished by making a function like nextGuess part of
the class as in how Read does it:
class Read a where
read :: Read a => String -> a
By definition then, any instance of read must provide a read function
capable of producing something of that type. So, it seems obvious the
solution to your problem is to make nextGuess part of the Guess class.
Alternatively if that's not really what you're trying to accomplish the
type signature of nextGuess is probably wrong. If you provide more detail
on what you're attempting to do maybe someone on here can suggest another
way of accomplishing it.
-R. Kyle Murphy
Curiosity was framed, Ignorance killed the cat.
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 = ...
> Thank you.
> Beginners mailing list
> Beginners at haskell.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Beginners