gpt4 book ai didi

由相同数据类型的不同构造函数共享的 Haskell 记录访问器

转载 作者:行者123 更新时间:2023-12-01 09:58:19 25 4
gpt4 key购买 nike

一个关于 Haskell 记录的基本问题。如果我定义这个数据类型,

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

以下作品:

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

但是如果我这样做,

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

我会收到此错误:Multiple declarations of 'name'

我想我直觉上理解为什么会这样,因为在第一种情况下 name 的类型只是 Pet -> String 而不管构造函数是什么用过的。但我不记得在我读过的任何一本 Haskell 书中看到过这条关于记录访问器函数的规则。有人可以对我在上面看到的行为给出更深入的解释吗?

最佳答案

来自Haskell '98 Report :

A data declaration may use the same field label in multiple constructors as long as the typing of the field is the same in all cases after type synonym expansion. A label cannot be shared by more than one type in scope. Field names share the top level namespace with ordinary variables and class methods and must not conflict with other top level names in scope.

我认为没有比这更深入的了。正如您所说,结果字段访问器无论如何都具有 Pet -> String 类型,因此决定的权力允许您在不同的构造函数中重复使用相同的字段名称很方便。

关于由相同数据类型的不同构造函数共享的 Haskell 记录访问器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20907974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com