How to disambiguate selector function?
Asked Answered
R

1

17

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?

Repel answered 23/5, 2016 at 15:35 Comment(1)
Ah, ambiguous record fields... wonder if the chain of kludgy fix extensions is infinite? If yes, will we need a DisambiguateRecordFieldsDisambiguationExtension extension? — ...Be sure to check out Nikita Volkov's records library, which should make these extensions completely unnecessary. — (FTR: I don't think the writers of these extensions are doing a bad job, in fact I've used RecordWildCards in the past and found it to work reasonably well. Nevertheless, I daresay it's overall not the right approach.)Danedanegeld
B
10

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

Bixby answered 23/5, 2016 at 15:40 Comment(10)
see the citation ... you are right but this is not how it works / is inferred - if you use signatures that is usually no problemBixby
oh i believe this LANGUAGE extension is going to be one of my favourite!Molal
yes it's extremely confusing ... I think I'm not gonna use it (in the same module)Bixby
Is this GHC 8.0 only?Tessellation
@Tessellation well obviously I am not competent to answer this but the page I linked says "This was implemented as ​Phab:D761 and ​Phab:D1391 and will be in GHC 8.0." so I would interpret that as yes - at the moment it's probably 8.x onlyBixby
@Carsten how to see (:t name) in GHCI?Pavis
@IvanKleshnin I don't understand your question - is :t name not working in GHCi ?Bixby
Not with double name declaration. """ Ambiguous occurrence ‘name’ It could refer to either the field ‘name’, defined at cc.hs:7:36 or the field ‘name’, defined at cc.hs:5:34 """Pavis
ah sorry I see your problem - you can use :i name in this case (it will find you both occurences)Bixby
also this should probably be an GHC issueBixby

© 2022 - 2024 — McMap. All rights reserved.