haskell - 容器元素类型

标签 haskell types containers

在某种程度上,这是我之前问题的倒退,但是......有人可以提醒我为什么这不起作用吗?

class Container c e where
  empty :: c
  insert :: e -> c -> c

instance Container [x] x where
  empty = []
  insert = (:)

instance Container ByteString Word8 where
  empty = BIN.empty
  insert = BIN.cons

instance Ord x => Container (Set x) x where
  empty = SET.empty
  insert = SET.insert

显然,如果这么简单,就没有人会费心去发明函数依赖或关联类型。那么上面的问题出在哪里呢?

最佳答案

没有什么可以阻止您添加instance Container [Int] Intinstance Container [Int] Char,并且当您要求empty::时[Int]编译器无法知道它应该来自哪个实例。

“啊,但我只有实例Container [Int] Int,”你说。 “无论如何,实例容器 [Int] Char 都会是一个错误。”

但是编译器无法知道您将来不会添加实例Container [Int] Char,如果您这样做了,也不允许它破坏您现有的代码。

所以我们需要某种方式告诉编译器

  • Container的第一个参数唯一确定Container的第二个参数
  • 如果它看到仅第二种类型不同的不同实例,则表明存在错误

输入函数依赖关系。

关于haskell - 容器元素类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9078168/

相关文章:

templates - Haskell - 自动使用导入模块中的变量

haskell - haskell 根据数据字段查找数据

haskell - 内联函数仍然显示在 .prof 文件中

types - 递归实现特征 "Not"

c++ - 如何在 C++ 中使用泛型 vector

haskell - haskell if-then-else 中递归调用 main 时执行多条语句

c++ - C++ 中的表实现

image - Docker 创建镜像失败

Java 对象的数组列表包含/等于

docker - Dockerize应用程序或机器?