[Haskell-cafe] A Very Simple Type Class Question

Frank Staals frank at fstaals.net
Tue Nov 11 20:46:59 UTC 2014


Larry Lee <llee454 at gmail.com> writes:

> 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

The only possible implementation for function f will be const
undefined. Your function f promises that given a value of type a, it can
return a value of *any* type b, as long as b is an instance of typeclass
A. So, once we are given a value of type a, we have to produce a value
of type b, however, we don't know what type b is! The only thing that we
know about things of type b is that they are an instance of A. This is
not enough information to be able to produce something of type 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)
>   <snip>


See the above: you are producing of type String. However, according to
the type signature, you should be able to produce something of an
arbitrary type b. Clearly that is not possible.

I am guessing that once you know the type a, you also know what the
output type b will be. If that is the case then you can use type
families: 

class A a where 
  type B a 
  f :: a -> B a 

instance A String where 
  type B String = String 
  f = id 


Hope this helps.

Regards, 

--

- Frank


More information about the Haskell-Cafe mailing list