Haskell:加载带有定义的文件失败,而在GHCi中交互加载效果很好。为什么? [英] Haskell: Loading a file with a definition fails, while doing it interactively in GHCi works well. Why?

查看:29
本文介绍了Haskell:加载带有定义的文件失败,而在GHCi中交互加载效果很好。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Win 10上使用GHCi 8.10.2。 我有一个名为srcLoadAndInteractiveDiffer.hs的源文件,其中只包含:

module LoadAndInteractiveDiffer where

testNothingIsNothing = Nothing == Nothing

将其加载到GHCi时,我收到:


Prelude> :l src/LoadAndInteractiveDiffer.hs
[1 of 1] Compiling LoadAndInteractiveDiffer ( srcLoadAndInteractiveDiffer.hs, interpreted )

srcLoadAndInteractiveDiffer.hs:3:24: error:
    * Ambiguous type variable `a0' arising from a use of `=='
      prevents the constraint `(Eq a0)' from being solved.
      Probable fix: use a type annotation to specify what `a0' should be.
      These potential instances exist:
        instance Eq Ordering -- Defined in `GHC.Classes'
        instance Eq Integer
          -- Defined in `integer-gmp-1.0.3.0:GHC.Integer.Type'
        instance Eq a => Eq (Maybe a) -- Defined in `GHC.Maybe'
        ...plus 22 others
        ...plus six instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    * In the expression: Nothing == Nothing
      In an equation for `testNothingIsNothing':
          testNothingIsNothing = Nothing == Nothing
  |
3 | testNothingIsNothing = Nothing == Nothing
  |                        ^^^^^^^^^^^^^^^^^^
Failed, no modules loaded.

但是,当我以交互方式执行相同的操作时,行为与预期一致:

-- Works fine:
Prelude> testNothingIsNothing = Nothing == Nothing
Prelude>

-- Works fine:
Prelude> testNothingIsNothing
True

我这里错过了什么?

推荐答案

您需要指定a的类型Maybe a。在ghci中,它进行猜测并将执行默认类型。

这里我们可以例如使用Integer,因为IntegerEq类型类的成员:

testNothingIsNothing = Nothing == (Nothing :: Maybe Integer)

GHCi具有extended defaulting rules [haskell-report]。因为这里只有Eq上类型约束a,所以它通常与Maybe ()一起工作。有关默认类型的详细信息,请参阅this article named "Type defaulting in Haskell" of Kwang's Haskell blog

您可以为带有语言杂注的文件启用扩展类型默认值:

{-# LANGUAGE ExtendedDefaultRules #-}

testNothingIsNothing = Nothing == Nothing
实际上,您可以为某些文件启用该功能,而对于其他文件则不可以。对于GGCI的交互部分,这是启用的。

这篇关于Haskell:加载带有定义的文件失败,而在GHCi中交互加载效果很好。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆