我试图理解 Haskell 的设计Data.Collection库,来自 Scala 背景。
It uses 功能依赖(其中有一个Scala 模拟)但它们的使用方式对我来说没有意义。在里面Unfoldable
类,复制如下,元素类型i
显示为取决于集合类型c
.
class Unfoldable c i | c -> i
具有不可观察元素的集合类。它是对偶的Foldable
class.
请解释一下依赖的作用c -> i
在这里发挥和设计意图,最好有一个使用示例?
该函数依赖性所表达的约束是给定集合类型的约束c
,其项目的类型i
已经确定了。例如,如果c ~ [a]
,即该集合是一个列表a
s,那么我们应该能够确定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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)