2017-01-27 83 views
1

我正在做一個Boolean數據的類型類實例,接受其他類型的布爾值,只是爲了好玩。我創建了數據Boolean,用於表示實際的Boolean值,並且我創建了一個名爲Booleanizable的類,該類表示可以轉換爲布爾值數據的值。問題如下:我想爲屬於Num類的每個類型聲明一個instance聲明,而不是爲每個類型聲明一個聲明。我怎麼做? 只是爲了使其更清晰,代碼:如何使另一種類型的類

module Boolean(
    Boolean, 
    true, 
    false, 
    Booleanizable 
) where 



data Boolean = Boolean Int 

false = Boolean 0 
true = Boolean 1 

instance Show Boolean where 
    show (Boolean 0) = "false" 
    show (Boolean 1) = "true" 

instance Eq Boolean where 
    (Boolean 0) == (Boolean 0) = True 
    (Boolean 0) == (Boolean 1) = False 
    (Boolean 1) == (Boolean 1) = True 
    (Boolean 1) == (Boolean 0) = False 



class Booleanizable a where 
    toBoolean :: (Booleanizable a) => a -> Boolean 

instance Booleanizable Boolean where 
    toBoolean (Boolean x) = Boolean x 

instance Booleanizable Bool where 
    toBoolean True = Boolean 1 
    toBoolean False = Boolean 0 

而且我想要做的事:

instance (Num a) => Booleanizable a where 
    toBoolean 0 = Boolean 0 
    toBoolean _ = Boolean 1 

這是出現錯誤:

Boolean.hs:37:21: 
    Illegal instance declaration for ‘Booleanizable a’ 
     (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 FlexibleInstances if you want to disable this.) 
    In the instance declaration for ‘Booleanizable a’ 
+2

請在問題中顯示您的嘗試出了什麼問題。 (在這種情況下,我能夠正確地猜出你得到了錯誤,但在其他問題,它可能是棘手做到這一點。) – duplode

+0

如果問題僅僅是錯誤'的限制是不超過實例head'較小,這裏是一個很好的解釋和解決方案(使用NEWTYPE) - http://stackoverflow.com/a/7198951/348716 –

+0

更新的問題。這不是那個錯誤。對不起,這麼久了@duplode –

回答

1

我做了三讓你的例子工作的東西:

1.)開始時,我添加了兩個語言擴展:

{-# LANGUAGE FlexibleInstances #-} 
{-# LANGUAGE UndecidableInstances #-} 

2.)我去除在類Booleanizable的定義中的自參照Booleanizable a

代替

class Booleanizable a where 
    toBoolean :: (Booleanizable a) => a -> Boolean 

使用

class Booleanizable a where 
    toBoolean :: a -> Boolean 

3.)我在最後一個實例定義中添加了附加約束Eq a

instance (Num a, Eq a) => Booleanizable a where 
    toBoolean 0 = Boolean 0 
    toBoolean _ = Boolean 1 
相關問題