鉴于以下代码,为什么Haskell只在到达第二个id
时报告错误?
data TypeX = TypeX {
id :: Int -- why not the error here?
, val :: String
} deriving (Show)
var1 = TypeX 1 "bananas"
var2 = TypeX {
val = "oranges"
, id = 2 -- why an error here?
}
错误是:
ghci> :l TypeX.lhs
[1 of 1] Compiling Main ( TypeX.lhs, interpreted )
TypeX.lhs:8:13:
Ambiguous occurrence ‘id’
It could refer to either ‘Main.id’, defined at TypeX.lhs:2:15
or ‘Prelude.id’,
imported from ‘Prelude’ at TypeX.lhs:1:1
(and originally defined in ‘GHC.Base’)
答案 0 :(得分:5)
定义记录字段并不是错误,即使它与从另一个模块导入的内容发生名称冲突。毕竟,您仍然可以通过显式为当前模块名称添加前缀来使用它:
Windows (CR LF)
还有一个语言扩展var2 = TypeX {
val = "oranges"
, Main.id = 2 -- no more error
}
,它使GHC在记录表示法中对字段名称稍微更加智能,并允许您的代码按原始编写。 (但它仍然不允许您为相同的模块中的两种不同类型定义相同的字段名称。)