简体   繁体   中英

Types required to be equivalent across two separate function calls

Consider the following two functions in Haskell (a minimal example of my real code):

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. 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?

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 :

{-# 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM