List instance
From HaskellWiki
(Difference between revisions)
(idioms) |
|||
| Line 78: | Line 78: | ||
</haskell> | </haskell> | ||
. | . | ||
| + | |||
| + | ---- | ||
| + | Or more generally, you can introduce a new class like | ||
| + | |||
| + | <haskell> | ||
| + | class IsChar a where | ||
| + | fromChar :: Char -> a | ||
| + | toChar :: a -> Char | ||
| + | instance IsChar Char where | ||
| + | fromChar = id | ||
| + | toChar = id | ||
| + | </haskell> | ||
| + | |||
| + | and then whenever you want to use the "<hask>a</hask>" type as a <hask>Char</hask>, you just convert it from/to <hask>Char</hask> with <hask>fromChar</hask>/<hask>toChar</hask> as appropriate. | ||
| + | |||
| + | == With FlexibleInstances == | ||
| + | The <hask>-XFlexibleInstances</hask> language extension is designed to solve this problem. See http://www.haskell.org/ghc/docs/6.8-latest/html/users_guide/type-class-extensions.html#instance-rules | ||
| + | |||
| + | <haskell> | ||
| + | {-# LANGUAGE FlexibleInstances #-} | ||
| + | instance C String where toX = ... | ||
| + | </haskell> | ||
== Source == | == Source == | ||
Revision as of 18:38, 10 May 2010
Contents |
1 Question
How to make a list type an instance of some type class in Haskell 98?
Haskell 98 does not support instances on particular composed types likeString
X
class C a where toX :: a -> X
I can define instances for
instance C Int where toX = ... instance C Double where toX = ... instance C Tuple where toX = ...
[Char]
instance C String where toX = ...
results in:
Illegal instance declaration for `C 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 `C String'
Is there some type class cleverness that can make this work in haskell 98? I can create a new wrapper type for strings:
newtype StringWrap = StringWrap String
and write an instance for that, but then I'll have to litter my code with calls to this constructor.
I'm aware of the approach taken by classShow
adds a extra method to the class:
class C a where toX :: a -> X listToX :: [a] -> X
X
[a]
X
[Char]
2 Answer
The trick in the Prelude is thatlistToX
If this is not possible in your application then introduce a new class like
class Element a where listToX :: [a] -> X
and define instances like
instance Element Char where listToX = ... instance Element a => C [a] where toX = listToX
.
Or more generally, you can introduce a new class like
class IsChar a where fromChar :: Char -> a toChar :: a -> Char instance IsChar Char where fromChar = id toChar = id
a
Char
Char
fromChar
toChar
3 With FlexibleInstances
The-XFlexibleInstances
{-# LANGUAGE FlexibleInstances #-} instance C String where toX = ...
4 Source
http://www.haskell.org/pipermail/haskell-cafe/2007-May/025742.html
Categories: FAQ | Idioms
