gpt4 book ai didi

haskell - 愚蠢的重复记录字段错误

转载 作者:行者123 更新时间:2023-12-03 15:12:15 25 4
gpt4 key购买 nike

考虑以下:

{-# LANGUAGE DuplicateRecordFields #-}

data A = A { name :: String }

data B = B { name :: String }

main = print $ name (A "Alice")

编译后,我收到以下消息(在 GHC 8.0.2 上)
duplicatedrecords.hs:7:16: error:
Ambiguous occurrence ‘name’
It could refer to either the field ‘name’,
defined at duplicatedrecords.hs:5:14
or the field ‘name’, defined at duplicatedrecords.hs:3:14

但是如果我修改 main行如下:
main = print $ name ((A "Alice") :: A)

编译成功进行。

为什么是这样?类型签名 :: A对我来说似乎是多余的, A构造函数让编译器清楚地知道 (A "Alice")A 类型.但由于某种原因,它有所作为。为什么会这样,有没有一种方法可以编译它而不会到处乱扔额外的类型签名?

注:

值得注意的是,以下编译良好:
data A = A { a_name :: String }
data B = B { b_name :: String }

class Name t where
name :: t -> String

instance Name A where name = a_name
instance Name B where name = b_name

main = print $ name (A "Alice")

我们甚至可以更进一步,允许不同的结果类型:
{-# LANGUAGE TypeFamilies #-}

data A = A { a_name :: String }
data B = B { b_name :: Int }

class Name t where
type family T t
name :: t -> T t

instance Name A where
type T A = String
name = a_name

instance Name B where
type T B = Int
name = b_name

main = print $ name (A "Alice")

似乎 GHC 只需要机械地为每个唯一的记录名称添加一个类,并为每个数据类型中的每个记录添加一个实例。然而,这将意味着 name x == name y并不暗示 x 的类型和 y是相同的,但我希望无论如何在使用此扩展程序时。

只是想知道我在这里是否遗漏了关于实现的任何棘手问题,或者它只需要有人来做吗?

最佳答案

-XDuplicateRecordFields目前不从参数推断类型。

GHC user guide section about this extension .

However, we do not infer the type of the argument to determine the datatype, or have any way of deferring the choice to the constraint solver. Thus the following is ambiguous:



但情况正在好转。所以我们可能期望并最终得到期望的行为:

https://prime.haskell.org/wiki/TypeDirectedNameResolution

关于haskell - 愚蠢的重复记录字段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44714711/

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