[Haskell-cafe] instance of String illegal
Donald Bruce Stewart
dons at cse.unsw.edu.au
Thu Sep 28 22:44:27 EDT 2006
adam:
> I am trying to create an instance of a class for String types. I have
> the following:
>
> class Foo a where
> mkFoo :: a -> String
>
> instance Foo String where
> mkFoo x = x
>
> and receive the following error:
>
> test.hs:9:0:
> Illegal instance declaration for `Foo String'
> (The instance type must be of form (T a b c)
> where T is not a synonym, and a,b,c are distinct type
> variables)
> In the instance declaration for `Foo String'
> Failed, modules loaded: none.
>
> I see that in general I am not able to create an instance of a class for any
> type [a], where a is a specific type.
Ok.
> class Foo a where
> mkFoo :: a -> String
N.B. The instance type must be of form (T a b c), where T is not a synonym.
One portable solution, introduce a newtype.
> newtype Strung = S String
> instance Foo Strung where
> mkFoo (S x) = x
*Main> mkFoo (S "foo")
"foo"
Alternatively, use -fglasgow-exts :)
> instance Foo String where
> mkFoo = id
$ ghci -fglasgow-exts A.hs
*Main> mkFoo "foo"
"foo"
-- Don
More information about the Haskell-Cafe
mailing list