2014-10-09 88 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特性應該被整合。