Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disambiguate selector function?

Tags:

haskell

ghc

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?

like image 314
ZhekaKozlov Avatar asked May 23 '16 15:05

ZhekaKozlov


1 Answers

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

like image 162
Random Dev Avatar answered Oct 16 '22 05:10

Random Dev