haskell源文件中的一行与GHCI中的一行之间的差异

ssm*_*ssm 5 haskell

Haskell新手在这里请原谅,如果问题太简单了.它只是我似乎无法处理为什么文件中的某些东西是好的,但在GHCI中没有.例如,我在文件中有以下行:

showLst :: [[Int]] -> IO ()
showLst = putStrLn . unlines . map show
Run Code Online (Sandbox Code Playgroud)

这需要一个m × n数组并在屏幕上打印结果.一个非常方便的功能.但是,当我快速检查GHCI并且我想要相同的功能时,我尝试在GHCI中定义相同的功能,如下所示:

>> let showLst = putStrLn . unlines . map show
>> showLst [[1,2,3], [4,5,6], [7,8,9]]
Run Code Online (Sandbox Code Playgroud)

我收到类型错误.所以我尝试了几种变化:

>> (showLst [[1,2,3], [4,5,6], [7,8,9]]) :: IO ()
>> (showLst:: [[Int]] -> IO ()) [[1,2,3], [4,5,6], [7,8,9]] 
>> (showLst [[1,2,3], [4,5,6], [7,8,9]]) :: [[Int]] -> IO () -- which us wrong anyway
>> showLst [[1,2,3], [4,5,6], [7,8,9]] :: [[Int]] -> IO () -- which is also wrong
Run Code Online (Sandbox Code Playgroud)

等等,他们都失败了.这似乎是一件非常简单的事情,但不确定为什么我发现这很困难.我必须遗漏一些非常重要的东西.有人可以让我知道我在做什么吗?

max*_*kin 10

问题是由于单态限制 GHCi默认类型的列表元素():

Prelude> let showLst = putStrLn . unlines . map show
Prelude> :t showLst 
showLst :: [()] -> IO ()
Run Code Online (Sandbox Code Playgroud)

您可以禁用此限制并获取常规类型:

Prelude> :set -XNoMonomorphismRestriction 
Prelude> let showLst = putStrLn . unlines . map show
Prelude> :t showLst 
showLst :: Show a => [a] -> IO ()
Run Code Online (Sandbox Code Playgroud)

或者您可以手动指定所需的类型:

Prelude> let showLst = putStrLn . unlines . map show :: [[Int]] -> IO ()
Run Code Online (Sandbox Code Playgroud)

  • 请注意,您还可以在GHCi中指定一个类型签名,使用`let showList :: [[Int]] - > IO(); showList = ...` (3认同)