[Haskell-cafe] A Very Simple Type Class Question

James M jmartin at eecs.berkeley.edu
Tue Nov 11 20:58:17 UTC 2014


First, there is an even simpler case that won't work:

class A a where
   foo :: a -> b

The question is what is 'b'. According to this b can be anything not
something specific. If you want 'b' to be something specific in must appear
as part of the type class declaration.

To do what you want to do, you could use the extension
MultiParamTypeClasses.

class A a

class (A a, A b) => B a b where
   foo :: a -> b

instance A Int

instance B Int Int where
    foo = id


Second, Haskell does not by default allow for type synonyms in instance
declarations. String is a type synonym of [Char]. If you want to use String
in instance declarations use the extension TypeSynonymInstances and
FlexibleInstances.

instance A String

instance A String String where
    foo = id


James

On Tue, Nov 11, 2014 at 12:59 PM, Larry Lee <llee454 at gmail.com> wrote:

> Hi
>
> I have a very simple problem.
> I have a class and want to define a function in that class that returns a
> different instance of the same class.
>
> I tried accomplishing this as follows:
>
>     class A a where
>       f :: A b => a -> b
>
>
> This fails however when I try to instantiate it. For example:
>
>     instance A String where
>       f x = x
>
>
> I get an error message that makes absolutely no sense to me:
>
>     src/CSVTree.hs:12:9:
>         Could not deduce (b ~ [Char])
>         from the context (A b)
>           bound by the type signature for f :: A b => String -> b
>           at src/CSVTree.hs:12:3-9
>           `b' is a rigid type variable bound by
>               the type signature for f :: A b => String -> b
>               at src/CSVTree.hs:12:3
>         In the expression: x
>         In an equation for `f': f x = x
>         In the instance declaration for `A String'
>     make: *** [compile] Error 1
>
> Can someone please explain: how I can achieve my goal; and why my code is
> failing; simply and in plain English.
>
> Thanks,
> Larry
> _______________________________________________
> 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/20141111/7c4bc87b/attachment-0001.html>


More information about the Haskell-Cafe mailing list