Haskell 中的函数依赖
我真的无法理解。为什么我们需要它?我的意思是,如果我使用相同的类型参数,我认为这意味着它们应该是相同的类型。
我听说它可以帮助编译器避免无限循环。有人可以告诉我一些更多细节吗?
最后,在现实世界 Haskell 中使用函数依赖时,我们是否应该遵循任何“模式和实践”?
[后续问题]
class Extract container element where
extract :: container -> element
instance Extract (a,b) a where
extract (x,_) = x
在上面的代码中,我对容器和元素使用了相同的类型变量“a”,我认为编译器可以因此推断这两种类型是相同的类型。
但是当我在 GHCi 中尝试这段代码时,我得到了以下反馈:
*Main> extract('x',3)
<interactive>:1:0:
No instance for (Extract (Char, t) element)
arising from a use of `extract' at <interactive>:1:0-13
Possible fix:
add an instance declaration for (Extract (Char, t) element)
In the expression: extract ('x', 3)
In the definition of `it': it = extract ('x', 3)
当其中一个已被指定为“Char”类型时,为什么另一个仍然是未解析的“element”类型?
I cannot really get it. Why do we need it at all? I mean if I use the same type parameter, I think that means they should be the same type.
I heard it can help the compiler to avoid the infinite loop. Can someone tell me some more details about that?
In the end, are there any 'patterns and practices' we should follow on the usage of functional dependency in Real World Haskell?
[Follow-up Question]
class Extract container element where
extract :: container -> element
instance Extract (a,b) a where
extract (x,_) = x
In the code above, I used the same type variable 'a' for both container and element, I think the compiler can thus infer that these two types are the same type.
But when I tried this code in GHCi, I got the following feedback:
*Main> extract('x',3)
<interactive>:1:0:
No instance for (Extract (Char, t) element)
arising from a use of `extract' at <interactive>:1:0-13
Possible fix:
add an instance declaration for (Extract (Char, t) element)
In the expression: extract ('x', 3)
In the definition of `it': it = extract ('x', 3)
When one of them has been specified to be type 'Char', why the other one is still unresolved type 'element'?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这解释得很好。所以基本上如果你有一个 -> 的 FD 关系b 这意味着对于类型类实例来说,任何“a”只能有一个“b”,所以 Int Int 但你也不能有 Int Float。这就是他们所说的“b”是由“a”唯一确定的意思。这可以扩展到任意数量的类型参数。需要它的原因是 1. 类型推断 2. 有时你需要这样的约束。
FD 的替代方案是类型族扩展,但不适用于所有 FD 情况。
I thought this explains it fairly well. So basically if you have an FD relation of a -> b all it means is for type-class instance there can only be one 'b' with any 'a' so Int Int but you can't have Int Float as well. That's what they mean when it's said that 'b' is uniquely determined from 'a'. This extends to any number of type paramters. The reason why it is needed is 1. Type inference 2. Sometimes you want a constraint like that.
An alternative to FDs is type families extension but not for all cases of FDs.