[Haskell-cafe] A Very Simple Type Class Question

Konstantine Rybnikov k-bx at k-bx.com
Tue Nov 11 20:48:35 UTC 2014


Larry,

By your definition

f x = x

this function returns whatever it got in it's argument, thus:
1. compiler infers that it's argument is of type String from
class-definition
2. String is actually a type-synonim for list of chars

        type String = [Char]

3. So now, on one hand function is returning something of a concrete type
[Char], and on the other (from class-definition) it should be some type
only restricted by operations on type-class.

Regarding your question on "how to do things properly" -- I'm not sure what
exactly are you trying to achieve. Could you describe a problem you're
trying to solve?

If you want to return something of type b, which is only constrainted by
being an instance of a type-class A, then you need to create it with a
function defined in class A. But since only function is f, it's not enough.
Here's an example of solution for the original "return something of another
instance" problem:

{-# LANGUAGE FlexibleInstances    #-}
{-# LANGUAGE TypeSynonymInstances #-}

class A a where
  f :: A b => a -> b
  def :: a

instance A Int where
  f x = def
  def = 4

instance A String where
  f x = def
  def = "asd"

main :: IO ()
main = print $ (f "asd" :: Int)

Cheers.

On Tue, Nov 11, 2014 at 10: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/20c20ea3/attachment.html>


More information about the Haskell-Cafe mailing list