record update syntax, equal property names in different types

162 Views Asked by At

say there are two different types of trees:

data Tree1 = Tree1 {name :: String, color :: String} deriving Show
data Tree2 = Tree2 {name :: String, age :: Integer} deriving Show

and consider the following default values for each type:

defaultTree1 = Tree1 "No Name" "green"
defaultTree2 = Tree2 "No Name" 10

By using record update syntax, now it's possible to create instances of both types as followed. E.g:

defaultTree1 {color = "brown"}
-- >
Tree1 {name = "No Name", color = "brown"}

When trying this with only the name "property", it we get an error:

defaultTree1 {name = "My Tree"}
    Couldn't match expected type ‘Tree2’ with actual type ‘Tree1’
    In the expression: defaultTree1
    In the expression: defaultTree1 {name = "My Tree"}

However, it works with Tree2:

defaultTree2 {name = "My Tree"}
-- >
Tree2 {name = "My Tree", age = 10}

What's the reason for this? How could an instance of Tree1 being created by using some default values?

0

There are 0 best solutions below