haskell - 避免 Haskell 中的 namespace 污染

标签 haskell namespaces types records

我在程序中使用许多不同的记录,其中一些使用相同的字段名称,例如

data Customer = Customer { ..., foo :: Int, ... }
data Product = Product { ..., foo :: Int, ... }

现在,由于访问器函数“foo”被定义了两次,我收到“多重声明”错误。避免这种情况的一种方法是使用完全限定导入的不同模块,或者简单地重命名字段(我不想这样做)。

Haskell 中处理此问题的官方建议方法是什么?

最佳答案

这是一个非常棘手的问题。有几个修复记录系统的建议。有关相关说明,请参阅TDNRrelated discussion on cafe .

使用当前可用的语言功能,我认为最好的选择是在两个不同的模块中定义两种类型,并进行合格的导入。除此之外,如果您愿意,您可以实现一些类型类机制。

在 Customer.hs 中

module Customer where
data Customer = Customer { ..., foo :: Int, ... }

在 Product.hs 中

module Product where
data Product = Product { ..., foo :: Int, ... }

在 Third.hs 中使用它们时

module Third where

import qualified Customer as C
import qualified Product as P

.. C.foo ..
.. P.foo ..

但是,我想在您遇到有关 recursively dependent modules 的问题之前还不算太晚。 .

关于haskell - 避免 Haskell 中的 namespace 污染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4260507/

相关文章:

if-statement - Haskell - do block 中的语法(使用 IO)

python - 在 Python 和 MySQL 中存储科学记数法的最有效方式

Html 类型值无效

c# - 具有不同设置和获取类型的访问器?

haskell - zip循环链表,哪种方式效率高?

haskell - 为什么此功能无法进行类型检查?

haskell - 在 Monad 链中对重复应用进行抽象

xml - 内联 svg 不显示图像

C++ 模板和访问命名空间

javascript - 在 ES6 中向对象字面量添加 const