考慮在Haskell以下兩個函數(我的實際代碼的最小示例):類型的呼叫
printSequence :: (Show a, Show b) => a -> b -> IO()
printSequence x y = (putStr . show) x >> (putStr . show) y
printSequence' :: (Show a, Show b) => a -> b -> IO()
printSequence' x y = print' x >> print' y
where print' = putStr . show
第一編譯好,但第二個產生錯誤:
Could not deduce (a ~ b)
from the context (Show a, Show b)
bound by the type signature for
printSequence' :: (Show a, Show b) => a -> b -> IO()
at test.hs:8:19-53
`a' is a rigid type variable bound by
the type signature for
printSequence' :: (Show a, Show b) => a -> b -> IO()
at test.hs:8:19
`b' is a rigid type variable bound by
the type signature for
printSequence' :: (Show a, Show b) => a -> b -> IO()
at test.hs:8:19
In the first argument of print', namely `y'
In the second argument of `(>>)', namely `(print' y)'
In the expression: (print' x) >> (print' y)
我知道這個錯誤意味着GHC是需要x
和y
等同類型。我不明白的是爲什麼。像print "fish" >> print 3.14
這樣的語句在解釋器中工作得非常好,那麼爲什麼GHC抱怨x
和y
是不同的類型,當我在兩個不同的時間調用我的print'
函數?
關於可怕的單態限制:http://stackoverflow.com/ question/32496864/what-is-the-monomorphism-restriction – chi