说有两种不同类型的树:
data Tree1 = Tree1 {name :: String, color :: String} deriving Show
data Tree2 = Tree2 {name :: String, age :: Integer} deriving Show
并考虑每种类型的以下默认值:
defaultTree1 = Tree1 "No Name" "green"
defaultTree2 = Tree2 "No Name" 10
通过使用记录更新语法,现在可以创建两种类型的实例,如下所示。 E.g:
defaultTree1 {color = "brown"}
-- >
Tree1 {name = "No Name", color = "brown"}
当只使用名称“property”进行尝试时,我们会收到错误:
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"}
但是,它适用于Tree2:
defaultTree2 {name = "My Tree"}
-- >
Tree2 {name = "My Tree", age = 10}
这是什么原因?如何使用一些默认值创建Tree1的实例?