Haskell record aggregators shared by different constructors of the same data type

The main question is about Haskell records. If I define this data type,

data Pet = Dog { name :: String } | Cat { name :: String } deriving (Show) 

The following work is carried out:

 main = do let d = Dog { name = "Spot" } c = Cat { name = "Morris" } putStrLn $ name d putStrLn $ name c 

But if I do this,

 data Pet = Dog { name :: String } | Cat { name :: Integer } deriving (Show) 

I will get this error: Multiple declarations of 'name' .

I think I intuitively understand why this should be so, since the type name in the first case is just Pet -> String regardless of the constructor used. But I don’t remember how I saw this rule about the write access functions in any of the Haskell books that I read. Can someone give a more detailed explanation of the behavior that I see above?

+3
source share
1 answer

From the Haskell '98 report:

A data label can use the same field label in several constructors, as long as the text input is the same in all cases after the extension of the type synonym. A label cannot be used by more than one type. Field names share the top-level namespace with ordinary class variables and methods and should not conflict with other top-level names in the scope.

I don’t think there is anything deeper there. As you said, the resulting field accessory is of type Pet -> String , so the permissions that will be resolved allow you to reuse the same field name in different constructors.

+7
source

Source: https://habr.com/ru/post/1273179/


All Articles