4

鉴于这种类型的同义词:

type Synonym a b = (a, b)

此代码在 GHCi 中不起作用:

ghci> let myFirst (f, s) = f :: Synonym a b -> a

<interactive>:1:21:
    Inferred type is less polymorphic than expected
      Quantified type variable `b' is mentioned in the environment:
        f :: Synonym a b -> a (bound at <interactive>:1:13)
      Quantified type variable `a' is mentioned in the environment:
        f :: Synonym a b -> a (bound at <interactive>:1:13)
    In the expression: f :: Synonym a b -> a
    In the definition of `myFirst':
        myFirst (f, s) = f :: Synonym a b -> a

但这确实:

ghci> let myFirst = fst :: Synonym a b -> a
-- no problem --

这只发生在我直接输入 GHCi 时;当我将它们放入文件和:load它们时,这两个定义都有效。

这里有什么问题?我已经多次遇到这个问题,但不明白为什么。

ps 我试过:set -XNoMonomorphismRestriction了,但这并没有什么不同。

4

1 回答 1

9

Haskell 正在尝试将类型签名与 匹配f,而不是匹配myFirst,但它不起作用(但我无法给出更多解释,其他人?)。即 Haskell 将其视为:

let myFirst (f,s) = (f :: Synonym a b -> a)

您可以解决此问题,提供单独的签名

let myFirst :: Synonym a b -> a; myFirst (f,s) = f

甚至使用 lambda(这本质上等同于myFirst = fst定义)

let myFirst = (\(f,s) -> f) :: Synonym a b -> a

(请注意,即使没有类型同义词,这也会失败:let myFirst (f,s) = f :: (a,b) -> a也不起作用。)

于 2012-08-20T13:31:02.550 回答