【问题标题】:Type inference of a function in GHCi differs with loaded from a fileGHCi 中函数的类型推断与从文件加载不同
【发布时间】:2014-08-19 09:22:57
【问题描述】:

我在test.hs中写了一个函数add'

add' = \x y -> x + y

然后我在 GHCi(版本 7.8.3)中加载了 test.hs,并输入了 :t add' 以查看 add' 是什么类型。结果看起来不正确:

*Main> :t add'
add' :: Integer -> Integer -> Integer

但是如果我直接在GHCi中输入:t (\x y -> x + y),结果是正确的:

*Main> :t (\x y -> x + y)
(\x y -> x + y) :: Num a => a -> a -> a

然后我尝试在test.hs 中重写add',如下所示,在 GHCi 中重写:type 它们:

add1 = \x y -> x + y
add2 = \x -> \y -> x + y
add3 x y = x + y

结果是:

add1 :: Integer -> Integer -> Integer
add2 :: Integer -> Integer -> Integer
add3 :: Num a => a -> a -> a

但是使用let 子句来定义一个函数,然后:type 他们或:type lambdas 直接在 GHCi all 导致Num a => a -> a -> a 的类型

为什么它们不同?是GHC的bug吗?

【问题讨论】:

  • 请注意add1add2 是完全等价的。

标签: haskell type-inference


【解决方案1】:

您点击了dreaded monomorphism restriction。单态限制使您的函数的类型签名专用于单一类型。您可以使用扩展名NoMonomorphismRestriction 关闭它:

{-# LANGUAGE NoMonomorphismRestriction #-}

add1 = \x y -> x + y
add2 = \x -> \y -> x + y
add3 x y = x + y

然后当您在 ghci 中加载类型时,它们将是:

λ> :t add1
add1 :: Num a => a -> a -> a
λ> :t add2
add2 :: Num a => a -> a -> a
λ> :t add3
add3 :: Num a => a -> a -> a

【讨论】:

  • 请注意,此行为已记录在 here
猜你喜欢
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
  • 2013-11-10
  • 1970-01-01
相关资源
最近更新 更多