问题描述
关于Haskell记录的一个基本问题。如果我定义了这个数据类型,
data Pet = Dog {name :: String} | Cat {name :: String}派生(显示)
以下工作:
main = do
let d = Dog {name =Spot}
c = Cat {name =Morris}
putStrLn $ name d
putStrLn $ name c
但是如果我这样做,
数据Pet = Dog {name :: String} | Cat {name :: Integer}派生(显示)
我会得到这个错误:多次声明'name'
。
我直觉地理解为什么会这样,因为第一种情况下 name
的类型是只需宠物 - >字符串
,不管使用的构造函数如何。但我不记得在我读过的任何Haskell书籍中看到有关记录访问函数的规则。有人可以对我在上面看到的行为稍作更深入的解释吗?
从:
I don认为还有更深入的东西。正如你所说,结果字段访问器的类型是 Pet - >字符串
无论如何所以权力决定它很方便,让您在不同的构造函数中重复使用相同的字段名称。
A basic question about Haskell records. If I define this datatype,
data Pet = Dog { name :: String } | Cat { name :: String } deriving (Show)
the following works:
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'll get this error: Multiple declarations of 'name'
.
I think I understand intuitively why this should be the case, since the type of name
in the first case is just Pet -> String
regardless of the constructor that was used. But I don't recall seeing this rule about record accessor functions in any of the Haskell books I've read. Can someone give a slightly more in-depth explanation about the behavior I'm seeing above?
From the Haskell '98 Report:
I don't think there's anything more in-depth to it. As you said, the resulting field accessor has the type Pet -> String
anyway so the powers that be decided it convenient to allow you to re-use the same field name in different constructors.
这篇关于Haskell记录访问器由具有相同数据类型的不同构造函数共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!