问题描述
我在一个程序中使用了许多不同的记录,其中一些使用相同的字段名称,例如
I'm using lots of different records in a program, with some of them using the same field names, e.g.
data Customer = Customer { ..., foo :: Int, ... }
data Product = Product { ..., foo :: Int, ... }
现在因为访问器函数foo"被定义了两次,我得到了多重声明"错误.避免这种情况的一种方法是使用完全限定的不同模块,或者简单地重命名字段(我不想这样做).
Now as the accessor function "foo" is defined twice, I get the "Multiple declarations" error. One way to avoid this would be using different modules that are imported fully qualified, or simply renaming the fields (which I don't want to do).
在 Haskell 中官方建议的处理方式是什么?
What is the officially suggested way of dealing with this in Haskell?
推荐答案
这是一个非常棘手的问题.有几个关于修复记录系统的建议.在相关说明中,请参阅 TDNR 和 cafe相关讨论.
This is a very hairy problem. There are several proposals for fixing the record system. On a related note, see TDNR and related discussion on cafe.
使用当前可用的语言特性,我认为最好的选择是在两个不同的模块中定义两种类型,并进行合格的导入.除此之外,如果你愿意,你可以实现一些类型类机制.
Using the currently available language features, I think the best option is defining the two types in two different modules, and doing a qualified import. On top of this, if you want, you can implement some type class machinery.
在 Customer.hs 中
In Customer.hs
module Customer where
data Customer = Customer { ..., foo :: Int, ... }
在 Product.hs 中
In Product.hs
module Product where
data Product = Product { ..., foo :: Int, ... }
在使用它们时,在 Third.hs
While using them, in Third.hs
module Third where
import qualified Customer as C
import qualified Product as P
.. C.foo ..
.. P.foo ..
然而,我想在你遇到关于的问题之前不会太晚递归依赖模块.
Yet, I imagine it won't be too late before you hit the problem about recursively dependent modules.
这篇关于在 Haskell 中避免命名空间污染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2