[英]Types required to be equivalent across two separate function calls
Consider the following two functions in Haskell (a minimal example of my real code):考虑 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
The first compiles fine, but the second produces the error:第一个编译正常,但第二个产生错误:
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)
I understand this error to mean that GHC is requiring x
and y
to be of equivalent type.我理解这个错误意味着 GHC 要求x
和y
是等效的类型。 What I do not understand is WHY.我不明白的是为什么。 Statements like print "fish" >> print 3.14
work perfectly fine in the interpreter, so why does GHC complain about x
and y
being different types when I call my print'
function two separate times?像print "fish" >> print 3.14
这样的语句在解释器中工作得非常好,那么当我两次调用我的print'
函数时,为什么 GHC 会抱怨x
和y
是不同的类型?
add an explicit type signature:添加显式类型签名:
printSequence' :: (Show a, Show b) => a -> b -> IO ()
printSequence' x y = print' x >> print' y
where
print' :: Show a => a -> IO ()
print' = putStr . show
or useNoMonomorphismRestriction
:或使用NoMonomorphismRestriction
:
{-# LANGUAGE NoMonomorphismRestriction #-}
printSequence' :: (Show a, Show b) => a -> b -> IO ()
printSequence' x y = print' x >> print' y
where
print' = putStr . show
then,然后,
\> printSequence' 5 "five"
5"five"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.