let myFirst (f, s) = f :: Synonym a b --6ren">
gpt4 book ai didi

haskell - 使用类型同义词的函数定义是 "less polymorphic than expected"

转载 作者:行者123 更新时间:2023-12-02 10:49:07 25 4
gpt4 key购买 nike

给定这种类型的同义词:

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 它们时,这两个定义都有效。

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

附:我尝试了 :set -XNoMonomorphismRestriction,但这并没有什么区别。

最佳答案

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 也不起作用。)

关于haskell - 使用类型同义词的函数定义是 "less polymorphic than expected",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12038479/

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