如何消除选择器功能? [英] How to disambiguate selector function?
问题描述
{ - #LANGUAGE DuplicateRecordFields# - }
data Dog = Dog {name :: String}
data Human = Human {name :: String}
dog = DogSpike
main = putStrLn $ name dog
这段代码无法编译:
不明确的出现`name'
它可以引用字段`name',在A.hs:4:22
处定义或者字段名称',定义在A.hs:3:18
如何正确检索我的狗的名字?
main = putStrLn $ name(dog :: Dog)
请参阅 DuplicateRecordFields 了解详情:
该字段的裸用途仅指选择器功能n,并且只有在明确的情况下才能使用。
和
然而,我们并不推断确定数据类型的参数类型,或者有任何推迟选择到约束求解器的方法。
这个例子非常类似于你:
bad(p :: Person)= personId p
当另一条记录的 personId
范围内的字段 - 即使它看起来很明显:(
In GHC 8:
{-# LANGUAGE DuplicateRecordFields #-}
data Dog = Dog { name::String }
data Human = Human { name::String }
dog = Dog "Spike"
main = putStrLn $ name dog
This code does not compile:
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
How to correctly retrieve the name of my dog?
this should work:
main = putStrLn $ name (dog :: Dog)
see DuplicateRecordFields for details:
Bare uses of the field refer only to the selector function, and work only if this is unambiguous.
and
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.
The example there is very much like yours:
bad (p :: Person) = personId p
this will not work when there is another record with a personId
field in scope - even if it seems to be obvious :(
这篇关于如何消除选择器功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!