【问题标题】:Role of functional dependency in `Unfoldable` typeclass of Haskell Collection API函数依赖在 Haskell Collection API 的 Unfoldable 类型类中的作用
【发布时间】:2016-11-29 13:58:51
【问题描述】:

我试图了解 Haskell 的 Data.Collection 库的设计,来自 Scala 文学背景。

它使用Functional Dependencies(有Scala analog),但它们的使用方式对我来说没有意义。在Unfoldable 类中,如下所示,元素类型i 显示为集合类型c 确定。

class Unfoldable c i | c -> i

具有不可观察元素的集合类。它是Foldable 类的对偶。

请解释一下依赖c -> i在这里扮演的角色和设计意图,最好是使用示例?

【问题讨论】:

    标签: haskell typeclass functional-dependencies


    【解决方案1】:

    该函数依赖表示的约束是,给定集合类型c,其项目i 的类型已经确定。例如,如果c ~ [a],即集合是as 的列表,那么我们应该能够确定i ~ a

    如果没有函数依赖,我们可以有两个实例,例如Unfoldable [a] a(明显/预期的实例)和Unfoldable [a] [a](类似于insert = concatsingleton = id)。如果类型检查器随后看到类似 empty :: [a] 的内容,它将无法选择使用哪个实例:

    {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
    
    class Unfoldable c i where
        empty :: c
    
    instance Unfoldable [a] a where
        empty = []
    
    instance Unfoldable [a] [a] where
        empty = []
    
    xs :: [a]
    xs = empty
    

    这会导致:

    No instance for (Unfoldable [a] i0) arising from a use of `empty'
    The type variable `i0' is ambiguous
    Relevant bindings include
      xs :: [a]
    Note: there are several potential instances:
      instance Unfoldable [a] a
      instance Unfoldable [a] [a]
    In the expression: empty
    In an equation for `xs': xs = empty
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      • 2018-06-12
      • 2018-12-10
      • 1970-01-01
      • 2015-03-08
      • 2019-01-27
      • 1970-01-01
      相关资源
      最近更新 更多