How to disambiguate selector function?

2019-03-25 09:15发布

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?

标签: haskell ghc
1条回答
走好不送
2楼-- · 2019-03-25 09:44

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

查看更多
登录 后发表回答