【发布时间】:2017-08-05 10:01:58
【问题描述】:
假设我有以下功能:
readList :: IO [Int]
readList = do
putStrLn "Please enter the list as a string"
putStrLn "Example: input of '1 2 3 4 5' will map to [1,2,3,4,5]"
line <- getLine
return $ map read $ words line
printNaive :: [Int] -> IO ()
printNaive xs = putStrLn "The maximum surpasser count is:" >> putStrLn "0"
main :: IO ()
main = readList >>= printNaive
此功能按预期工作。现在假设我打算将此代码扩展为更通用,并将任何类型的东西作为列表读入一行:
readList :: (Read a, Int a) -> IO [a]
readList = do
putStrLn "Please enter the list as a string"
putStrLn "Example: input of '1 2 3 4 5' will map to [1,2,3,4,5]"
line <- getLine
return $ map read $ words line
printNaive :: (Eq a) => [a] -> IO ()
printNaive xs = putStrLn "The maximum surpasser count is:" >> putStrLn "0"
main :: IO ()
main = readList >>= printNaive
这失败了:
Ambiguous type variable ‘a0’ arising from a use of ‘Lib.readList’
prevents the constraint ‘(Read a0)’ from being solved.
Probable fix: use a type annotation to specify what ‘a0’ should be.
These potential instances exist:
instance Read Ordering -- Defined in ‘GHC.Read’
instance Read Integer -- Defined in ‘GHC.Read’
instance Read a => Read (Maybe a) -- Defined in ‘GHC.Read’
...plus 22 others
...plus four instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
我将如何编写这段代码,因为我真的不在乎它是什么类型的东西,只要它符合Eq。
另外,假设我想提供一种工具来指定列表将包含的类型。 (通过另一个 getLine 说)。
如何从getLine 中提取类型,然后如何将map read $ words line 中的每个元素转换为该特定类型。
【问题讨论】:
-
请发布导致此错误的确切代码。在最小化过程中不要走捷径并猜测哪些代码。验证,方法是把它放在一个单独的文件中,并检查它确实给了你预期的错误。
-
您可能只需从您的函数中删除类型签名,然后使用 ghci 向 ghc 询问最通用的类型,加载您的程序并输入
:t readList -
编辑问题以包含更多代码,因为原始集实际上并不是一个最小的可重现示例
-
@AbrahamP 您仍然没有成功提供与出现的错误匹配的代码。
-
根本不可能不关心它是什么类型。
标签: haskell types type-conversion typeclass