ghci中的错误,我无法在写入的haskell文件中重现

时间:2014-04-03 13:48:19

标签: haskell ghci runhaskell

我尝试使用ghci检查this stackoverflow answer并收到以下错误:

> import Data.List
> let m = head . sort
> m [2,3,4]

<interactive>:5:4:
   No instance for (Num ()) arising from the literal `2'
   Possible fix: add an instance declaration for (Num ())
   In the expression: 2
   In the first argument of `m', namely `[2, 3, 4]'
   In the expression: m [2, 3, 4]

不幸的是我无法在写入的haskell文件中重现错误:

-- file.hs
import Data.List

main = do
    let m = head . sort
    putStrLn $ show $ m [2,3,4]

使用runhaskell file.hs运行此文件可获得预期值2。我在ghci会话中的错误是什么?

编辑:我注意到,函数m在ghci中有一个奇怪的类型:

> import Data.List
> let m = head . sort
> :t m
m :: [()] -> ()

为什么会这样?它不应该有Ord a => [a] -> a类型吗?对于sorthead,我得到了预期的类型:

> :t sort
sort :: Ord a => [a] -> [a]
> :t head
head :: [a] -> a

1 个答案:

答案 0 :(得分:7)

这是可怕的单态限制的错误。基本上,因为您没有为m指定类型,所以GHCi会为您猜测它。在这种情况下,它猜测m应该具有类型[()] -> (),即使这显然不是您想要的。只需在m中为GHCi提供类型签名,您就可以了。

> :set +m  -- multiline expressions, they're handy
> let m :: Ord a => [a] -> a
|     m = head . sort

您可以使用

禁用Monomorphism限制
> :set -XNoMonomorphismRestriction

但它通常非常方便,否则您必须为通常不会以交互模式指定的内容指定许多类型。

相关问题