[Haskell-cafe] Query regarding Type classes
Arun Suresh
arun.suresh at gmail.com
Mon Oct 13 06:18:21 EDT 2008
Hello Ryan..
On Mon, Oct 13, 2008 at 3:33 PM, Ryan Ingram <ryani.spam at gmail.com> wrote:
> Step 1: Forget everything you know about OO classes, then try again :)
you seem to have read my mind [:)].. i actaually hit upon this issue while
trying to "transcode" some C++ to Haskell..
>
>
> 2008/10/13 Arun Suresh <arun.suresh at gmail.com>:
> > class Foo a where
> > fooFunc :: a -> Int
> >
> > data FooData = FData
> >
> > instance Foo FooData where
> > fooFunc _ = 10
>
> So far so good.
>
> > class Bar a where
> > barFunc :: (Foo b) => a -> b -> Int
>
> So now, barFunc advertises "for any type a which is in the Bar
> typeclass, and any type b which is in the Foo typeclass, I can give
> you a function from a to b to Int". You can make an implementation of
> this that has different functionality based on "a", but it needs to be
> polymorphic in "b", taking any type "b" which is a member of Foo.
>
> > data BarData = BData
> >
> > instance Bar BarData where
> > barFunc _ FData = 20
>
> Uh oh! FData is of type FooData! But we just advertised that we
> could take *anything* which is in the typeclass Foo, which can include
> any number of other types. It doesn't matter that FooData is the only
> declared member at this point. What that means is that if you want to
> do anything with the second argument, you can only use functions that
> accept any type which is a member of the Foo class. Right now that
> just means generically polymorphic functions (id, const, etc.), and
> the fooFunc function inside the "Foo" typeclass.
>
> For example, this declaration would work:
>
> instance Bar BarData where
> barFunc _ f = 10 + fooFunc f
>
> > When I compile I get this :
> > Couldn't match expected type `b' against inferred type `FooData'
> > `b' is a rigid type variable bound by
> > the type signature for `barFunc' at Sample.hs:16:20
> > In the pattern: FData
> > In the definition of `barFunc': barFunc _ FData = 20
> > In the definition for method `barFunc'
>
> The compiler is just telling you what I just told you: barFunc says
> that it should take any type "b", but the pattern FData constrains the
> argument to be a FooData.
>
> > Think Im missing something really big...
> > Could somebody kindly help me out here...
>
> I recommend reading http://www.haskell.org/haskellwiki/OOP_vs_type_classes
Thanks...
Arun
>
> -- ryan
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20081013/ecb19665/attachment.htm
More information about the Haskell-Cafe
mailing list