
[英]Type error in Haskell when pattern matching against Maybe with Show constraint
[英]Show Constraint type in haskell
我正在嘗試使用show function打印到zer或one的控制台值,但是我做不到。 這是我的代碼:
{-# LANGUAGE NoMonomorphismRestriction #-}
import Control.Arrow
import Data.List
import qualified Data.Map as M
import Data.Function
class Eq a => Bits a where
zer :: a
one :: a
instance Bits Int where
zer = 0
one = 1
instance Bits Bool where
zer = False
one = True
instance Bits Char where
zer = '0'
one = '1'
我正在嘗試使用函數show將zer或一個轉換為字符串。 所以我嘗試了:
k = zer
show k
但是我得到這個錯誤
<interactive>:10:1: error:
• Ambiguous type variable ‘a0’ arising from a use of ‘show’
prevents the constraint ‘(Show a0)’ from being solved.
Probable fix: use a type annotation to specify what ‘a0’ should be.
These potential instances exist:
instance (Show k, Show a) => Show (M.Map k a)
-- Defined in ‘containers-0.5.7.1:Data.Map.Base’
instance Show Ordering -- Defined in ‘GHC.Show’
instance Show Integer -- Defined in ‘GHC.Show’
...plus 24 others
...plus 11 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the expression: show zer
In an equation for ‘it’: it = show zer
所以我試圖創建實例來顯示。 所以我將其添加到我的代碼中:
instance (Show a) => Show (Bits a) where
show zer = "0"
show one = "1"
但是我又遇到一個錯誤
main.hs:25:28: error:
• Expected a type, but ‘Bits a’ has kind ‘Constraint’
• In the first argument of ‘Show’, namely ‘Bits a’
In the instance declaration for ‘Show (Bits a)’
你能告訴我我做錯了什么嗎?
您試圖使一個類成為一個類的實例,而不是使一個類型成為一個類的實例。 相比:
Show a => Show (Bits a) -- Invalid
至
Show a => Show (Maybe a) -- Valid
其中Maybe
是數據類型,而Bits
是類名稱。
我認為不可能表達“任何具有Bits
實例的實例都具有Show
實例的實例”,因為它可能導致實例重疊 :如果您可以定義類似的實例 ,則在使用show :: Int -> String
the編譯器不知道是使用Show Int
的Prelude實例,還是使用Int
作為Bits
的實例定義的show
。
一個麻煩的解決方法可能是強制執行“另一個方向”:每個Bits
實例必須是Show
的實例,這將允許您使用a
Show
實例,而不是您自己的Show
實例:
class (Show a, Eq a) => Bits a where
zer :: a
one :: a
main = print (zer :: Int)
盡管這需要顯式的類型簽名來解決呼叫站點上zer
類型的歧義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.