2012-03-22 67 views
1
data Maybe' a = Nothing' | Just' a deriving (Show) 

class From' t 
    where from' :: t a -> a 

instance From' Maybe' 
    where from' (Just' x) = x 

This works。功能和類別之間的類型簽名

但是......

from2 :: t a -> a 
from2 (Just' x) = x 

Couldn't match type `t' with `Maybe'' 
    `t' is a rigid type variable bound by 
     the type signature for from2 :: t a -> a at test.hs:11:1 
In the pattern: Just' x 
In an equation for `from2': from2 (Just' x) = x 

我不知道爲什麼它不工作。

回答

4

在此例中,t定義爲Maybe',因此from'必須具有類型Maybe' a -> a。如果你寫:

from2 :: Maybe' a -> a 

然後它會工作。該錯誤消息是說,你的類型的簽名聲稱from2可以把t aa任何選擇t,但你的定義只有tMaybe'工作。

順便說一句,這個功能已經爲標準Maybe類型爲Data.Maybe模塊中fromJust定義,但你可能,如果你給它傳遞Nothing不應該使用它,因爲它會給無益的錯誤消息。當然,如果只是一個例子,那就沒關係。

+1

這只是一個例子。謝謝! ehird。你是個好人。 – user1286894 2012-03-22 20:38:39

+0

沒問題:)如果我的回答對你有幫助,你應該點擊旁邊的複選標記,以便問題被標記爲已解決。 – ehird 2012-03-22 20:40:41

+0

@ehird:他使用的類型是「Maybe」,而不是「Maybe」。你應該更正你的答案,添加缺少的''':) – 2012-03-22 22:13:10