在 GHC 8 中:
{-# LANGUAGE DuplicateRecordFields #-}
data Dog = Dog { name::String }
data Human = Human { name::String }
dog = Dog "Spike"
main = putStrLn $ name dog
此代码无法编译:
Ambiguous occurrence `name'
It could refer to either the field `name', defined at A.hs:4:22
or the field `name', defined at A.hs:3:18
如何正确检索我的狗的名字?
最佳答案
这应该工作:
main = putStrLn $ name (dog :: Dog)
见 DuplicateRecordFields详情:
Bare uses of the field refer only to the selector function, and work only if this is unambiguous.
和
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.
那里的例子和你的很像:
bad (p :: Person) = personId p
当有另一条记录为
personId
时,这将不起作用范围内的字段 - 即使看起来很明显:(
关于haskell - 如何消除选择器功能的歧义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37395098/