gpt4 book ai didi

haskell - 为什么 GHC 和 GHCI 在类型推断上有所不同?

转载 作者:行者123 更新时间:2023-12-02 21:32:27 25 4
gpt4 key购买 nike

我注意到,在做codegolf challenge时,默认情况下,GHC 不会推断变量的最通用类型,当您尝试将其与两种不同类型一起使用时,会导致类型错误。

例如:

(!) = elem
x = 'l' ! "hello" -- From its use here, GHC assumes (!) :: Char -> [Char] -> Bool
y = 5 ! [3..8] -- Fails because GHC expects these numbers to be of type Char, too

这可以使用编译指示NoMonomorphismRestriction进行更改。

但是,将其输入 GHCI 不会产生类型错误,并且 :t (!) 表明,此处假设 (Foldable t, Eq a) => a -> t a -> Bool,即使使用 -XMonomorphismRestriction 显式运行时也是如此。

为什么 GHC 和 GHCI 在假设函数的最通用类型方面存在差异?

(另外,为什么默认情况下启用它?它有什么帮助?)

最佳答案

委员会做出这一决定的背景,用设计师自己的话说,在文章“A History of Haskell: Being Lazy with Class”中给出。 ” 作者:Paul Hudak 等人

A major source of controversy in the early stages was the so-called “monomorphism restriction.” Suppose that genericLength has this overloaded type:

genericLength :: Num a => [b] -> a

Now consider this definition:

f xs = (len, len)`
where
len = genericLength xs

It looks as if len should be computed only once, but it can actually be computed twice. Why? Because we can infer the type len :: (Num a) => a; when desugared with the dictionary-passing translation, len becomes a function that is called once for each occurrence of len, each of which might used at a different type.

[John] Hughes argued strongly that it was unacceptable to silently duplicate computation in this way. His argument was motivated by a program he had written that ran exponentially slower than he expected. (This was admittedly with a very simple compiler, but we were reluctant to make performance differences as big as this dependent on compiler optimisations.)

Following much debate, the committee adopted the now-notorious monomorphism restriction. Stated briefly, it says that a definition that does not look like a function (i.e. has no arguments on the left-hand side) should be monomorphic in any overloaded type variables. In this example, the rule forces len to be used at the same type at both its occurrences, which solves the performance problem. The programmer can supply an explicit type signature for len if polymorphic behaviour is required.

The monomorphism restriction is manifestly a wart on the language. It seems to bite every new Haskell programmer by giving rise to an unexpected or obscure error message. There has been much discussion of alternatives.

(18,强调已添加。)请注意,John Hughes 是本文的合著者。

关于haskell - 为什么 GHC 和 GHCI 在类型推断上有所不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44123666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com