Haskell记录访问器由具有相同数据类型的不同构造函数共享 [英] Haskell record accessors shared by different constructors of the same data type

查看:112
本文介绍了Haskell记录访问器由具有相同数据类型的不同构造函数共享的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于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书籍中看到有关记录访问函数的规则。有人可以对我在上面看到的行为稍作更深入的解释吗?

解决方案

Haskell '98 Report


数据声明可以在多个构造函数中使用相同的字段标签,只要字段的输入在类型同义词扩展之后的所有情况下都是相同的。范围内的标签不能由多个类型共享。字段名称与普通变量和类方法共享顶级名称空间,并且不能与作用域中的其他顶级名称冲突。


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:

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.

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记录访问器由具有相同数据类型的不同构造函数共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆