[Haskell-beginners] instances of different kinds
Greg
greglists at me.com
Fri Aug 27 04:58:34 EDT 2010
Hi--
More silly typeclass questions. I'm not sure the right way to ask it, so I'll start with a failed code snippet:
data Foo a = Foo a
class TwoPi a where
div2pi :: (Floating b) => a -> b
instance (Floating a) => TwoPi (Foo a) where
div2pi (Foo a) = a / (2*pi)
instance TwoPi Float where
div2pi a = a / (2*pi)
This code is obviously meaningless, but I'm trying to figure out how you can create instances of a typeclass for data types of different kinds.
I have a similar piece of code that works:
data Foo a = Foo a
class Testable a where
isPos :: a -> Bool
instance (Ord b, Num b) => Testable (Foo b) where
isPos (Foo b) = b > 0
instance Testable Float where
isPos a = a > 0
One obvious difference is that the type of isPos is a -> Bool, with a defined type as the return. I'd rather not commit to a specific Floating type up front (I'd prefer sometimes Float sometimes Double, depending on the 'a' in Foo a, but trying to declare it as Float doesn't help me. This fails:
data Foo a = Foo a
class TwoPi a where
div2pi :: a -> Float
instance (Floating b) => TwoPi (Foo b) where
div2pi (Foo b) = b / (2*pi)
instance TwoPi Float where
div2pi a = a / (2*pi)
The errors I'm getting are various permutations of:
Couldn't match expected type `Float' against inferred type `b'
`b' is a rigid type variable bound by
the instance declaration at gcbTestBad.hs:8:19
In the expression: b / (2 * pi)
In the definition of `div2pi': div2pi (Foo b) = b / (2 * pi)
In the instance declaration for `TwoPi (Foo b)'
What is the difference between these last two cases ("a -> Bool" and "a -> Float"), and is there anyway to make "a -> b" work?
Thanks--
Greg
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20100827/cf08a228/attachment.html
More information about the Beginners
mailing list