避免Haskell中的名称空间污染 [英] Avoiding namespace pollution in Haskell
问题描述
我在一个程序中使用了很多不同的记录,其中一些使用了相同的字段名称,例如
data Customer = Customer {...,foo :: Int,...}
data Product = Product {...,foo :: Int,...}
现在,访问器函数foo被定义了两次,我得到了多个声明错误。避免这种情况的一种方法是使用不同的模块进行完全限定,或者只是重新命名字段(我不想这样做)。
什么是正式提出在Haskell中处理这个问题的方法?
这是一个非常棘手的问题。有几个提议用于修复记录系统。在相关说明中,请参阅 TDNR 和关于咖啡馆的相关讨论。
使用当前可用的语言功能,我认为最好的选择是在两个不同的模块中定义两种类型,并进行合格的导入。除此之外,如果你愿意的话,你可以实现一些类型的类机器。
在Customer.hs中
module Customer其中
data Customer = Customer {...,foo :: Int,...}
在Product.hs中
模块产品其中
数据Product = Product {...,foo :: Int,...}
使用它们时,在Third.hs中
模块第三个其中
将合格的客户导入为C
导入限定产品为P
.. C.foo ..
.. P.foo ..
然而,我想在你遇到递归依赖模块。
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, ... }
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).
What is the officially suggested way of dealing with this in Haskell?
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.
In Customer.hs
module Customer where
data Customer = Customer { ..., foo :: Int, ... }
In Product.hs
module Product where
data Product = Product { ..., foo :: Int, ... }
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中的名称空间污染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!