[Haskell-cafe] A Very Simple Type Class Question
Taylor Hedberg
t at tmh.cc
Tue Nov 11 21:49:13 UTC 2014
The caller of your function f, rather than the implementation of f, gets to
decide which instance of A f should return. In other words, f's
implementation must be polymorphic in its return type. Your example f
x = x does
not satisfy that property. That implementation has type f :: A a => a -> a,
not the required type f :: (A a, A b) => a -> b.
The error message is saying that, from the class definition, GHC has
deduced that f must return a value of type A b => b, but your
implementation is returning a String (a.k.a. [Char]) instead. The notation b
~ [Char] means "b is equivalent to [Char]".
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/4bc4a6a0/attachment-0001.html>
More information about the Haskell-Cafe
mailing list