2014-10-09 89 views
1

让我的问题之前,让我说出我的理解(也许是不正确的),一个列表[]是更高kinded类型:制作类型类的实例列表

ghci> :kind [] 
[] :: * -> * 

我可能是错误的,但是,一个[]需要一个类型,因为它是一个List of some type 'T'

现在我的问题。

class Foo a where 
    bar :: String -> a 

然后,我尝试创建一个Foo [String]。我的理解是在Foo a[String]。所以,我期望bar返回[String]

instance Foo [String] where 
    bar [] = [] 
    bar (x:_) = [x] 

不过,我得到以下编译时错误:

ghci> :l TypeClassExample.hs 
[1 of 1] Compiling Main    (TypeClassExample.hs, interpreted) 

TypeClassExample.hs:5:10: 
    Illegal instance declaration for `Foo [String]' 
     (All instance types must be of the form (T a1 ... an) 
     where a1 ... an are *distinct type variables*, 
     and each type variable appears at most once in the instance head. 
     Use -XFlexibleInstances if you want to disable this.) 
    In the instance declaration for `Foo [String]' 
Failed, modules loaded: none. 

我犹豫不理解它添加这个编译时标志。

这个简单代码的意义是什么?

+0

你仍然有一个错误'bar(x:_)= [[x]]'必须在实例 – viorior 2014-10-09 15:34:14

+0

你能说更多吗?我想你是说我有一个非详尽的比赛?但是,这2起案件应该与所有案件相匹配,我认为,不是吗? – 2014-10-09 16:55:27

+0

@Kevin_Meredith'x :: Char',和'bar :: String - > [String]',但是'[x] :: String',所以'[[x]] :: [String]' – viorior 2014-10-10 07:11:49

回答

3

Haskell语言定义是相当限制性的,并且只允许列表实例是形式

instance ... => Foo [a] where 

其中在头部a正是一个类型变量a,例如不允许[Int][String]

但是,您可以要求GHC忽略此限制。只需在你的文件的第一个开头添加以下内容:

{-# LANGUAGE FlexibleInstances #-} 

很多很多现代Haskell程序都使用它。可以说,在下一个Haskell定义修订版中,这个GHC特性应该被整合。