How to disambiguate selector function?

2019-03-25 09:44发布

问题:

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?

回答1:

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 :(



标签: haskell ghc