如何重用不同类型的IO提升功能?

时间:2014-09-17 13:14:31

标签: haskell type-inference

以下代码

import Control.Applicative
import Control.Arrow
import Data.List.Split

main :: IO ()
main = do
    ints <- getNumberLine
    integers <- getNumberLine
    print $ foo ints integers

getNumberLine = readDataLine <$> getLine

readDataLine :: Read a => String -> [a]
readDataLine = splitOn " " >>> map read

foo :: [Int] -> [Integer] -> String
foo _ _ = "hello"

给出了以下错误消息:

GetNumberLine.hs:9:22:
    Couldn't match type `Int' with `Integer'
    Expected type: [Integer]
      Actual type: [Int]
    In the second argument of `foo', namely `integers'
    In the second argument of `($)', namely `foo ints integers'
    In a stmt of a 'do' block: print $ foo ints integers
Failed, modules loaded: none.

只有在我创建第二个getNumberLine函数时才有效:

import Control.Applicative
import Control.Arrow
import Data.List.Split

main :: IO ()
main = do
    ints <- getNumberLine
    integers <- getNumberLine2
    print $ foo ints integers

getNumberLine = readDataLine <$> getLine
getNumberLine2 = readDataLine <$> getLine

readDataLine :: Read a => String -> [a]
readDataLine = splitOn " " >>> map read

foo :: [Int] -> [Integer] -> String
foo _ _ = "hello"

我觉得很难看。

为什么这有必要?还有更好的方法吗?

1 个答案:

答案 0 :(得分:5)

你被Dreaded monomorphism restriction咬了。最简单的解决方法是在函数中添加类型签名:

getNumberLine :: Read a => IO [a]
getNumberLine = readDataLine <$> getLine

有关之前的SO讨论,请参阅here