编译时haskell“模棱两可的类型变量”,但粘贴到ghci时工作正常

问题描述

我有以下内容

import qualified Data.Map as M

incr c a = M.insertWith (+) a 1 c
counter = foldl incr M.empty

main = print 5

当我尝试在 macOS 上使用 ghc 版本 8.8.4 进行编译时,我遇到了一大堆错误(如下)。但是,当我将每一行(通过粘贴)手动执行到 ghci 中时,没有错误

为什么此代码ghci 中有效,但在我尝试编译或 :load 时无效?

Bar.hs:4:11: error:
    • Ambiguous type variable ‘t0’ arising from a use of ‘foldl’
      prevents the constraint ‘(Foldable t0)’ from being solved.
      Relevant bindings include
        counter :: t0 k0 -> M.Map k0 Integer (bound at Bar.hs:4:1)
      Probable fix: use a type annotation to specify what ‘t0’ should be.
      These potential instances exist:
        instance Foldable (Either a) -- Defined in ‘Data.Foldable’
        instance Foldable (M.Map k) -- Defined in ‘Data.Map.Internal’
        instance Foldable Maybe -- Defined in ‘Data.Foldable’
        ...plus two others
        ...plus 26 instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In the expression: foldl incr M.empty
      In an equation for ‘counter’: counter = foldl incr M.empty
  |
4 | counter = foldl incr M.empty
  |           ^^^^^^^^^^^^^^^^^^

Bar.hs:4:17: error:
    • Ambiguous type variable ‘k0’ arising from a use of ‘incr’
      prevents the constraint ‘(Ord k0)’ from being solved.
      Relevant bindings include
        counter :: t0 k0 -> M.Map k0 Integer (bound at Bar.hs:4:1)
      Probable fix: use a type annotation to specify what ‘k0’ should be.
      These potential instances exist:
        instance (Ord a,Ord b) => Ord (Either a b)
          -- Defined in ‘Data.Either’
        instance (Ord k,Ord v) => Ord (M.Map k v)
          -- Defined in ‘Data.Map.Internal’
        instance Ord Ordering -- Defined in ‘GHC.Classes’
        ...plus 24 others
        ...plus 38 instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In the first argument of ‘foldl’,namely ‘incr’
      In the expression: foldl incr M.empty
      In an equation for ‘counter’: counter = foldl incr M.empty
  |
4 | counter = foldl incr M.empty
  |                 ^^^^

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)