【问题标题】:Role of functional dependency in `Unfoldable` typeclass of Haskell Collection API函数依赖在 Haskell Collection API 的 Unfoldable 类型类中的作用
【发布时间】:2016-11-29 13:58:51
【问题描述】:
【问题讨论】:
标签:
haskell
typeclass
functional-dependencies
【解决方案1】:
该函数依赖表示的约束是,给定集合类型c,其项目i 的类型已经确定。例如,如果c ~ [a],即集合是as 的列表,那么我们应该能够确定i ~ a。
如果没有函数依赖,我们可以有两个实例,例如Unfoldable [a] a(明显/预期的实例)和Unfoldable [a] [a](类似于insert = concat,singleton = 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