两个单独的函数调用需要等效的类型

时间:2016-03-06 02:16:21

标签: haskell types ghci type-systems

考虑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要求xy具有相同的类型。我不明白的是为什么。像print "fish" >> print 3.14这样的语句在解释器中工作得非常好,那么为什么GHC会在我分别两次调用x函数时抱怨yprint'是不同的类型?

1 个答案:

答案 0 :(得分:1)

添加显式类型签名:

printSequence' :: (Show a, Show b) => a -> b -> IO ()
printSequence' x y = print' x >> print' y
    where
    print' :: Show a => a -> IO ()
    print' = putStr . show

或使用NoMonomorphismRestriction

{-# LANGUAGE NoMonomorphismRestriction #-}

printSequence' :: (Show a, Show b) => a -> b -> IO ()
printSequence' x y = print' x >> print' y
    where
    print' = putStr . show

然后,

\> printSequence' 5 "five"
5"five"