[Haskell-cafe] A Very Simple Type Class Question

Andrew Gibiansky andrew.gibiansky at gmail.com
Tue Nov 11 20:10:47 UTC 2014


When you declare a type signature such as

f :: C x => a -> b

there is an implicit "forall":

f :: forall x. C x => a -> x

That is, the type signature must hold *for all* x such that C x holds.
However, in your case, it only holds for String – while A String does hold,
that is irrelevant, because the type signature states that it must hold for
*any* x such that A x that the caller wants. To put it another way, the
caller decides the "b" in that type signature, not the function
implementation.

What you want is something like

f :: exists x. C x => a -> x

so that f will return some unknown value such that you know it is an
instance of C x.

Hope that helps,
Andrew

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/55f6b563/attachment-0001.html>


More information about the Haskell-Cafe mailing list