8

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'?

4

1 回答 1

8

我认为这很好地解释了它。所以基本上,如果你有一个 a -> b 的 FD 关系,这意味着对于类型类实例,只能有一个 'b' 和任何 'a' 所以 Int Int 但你也不能有 Int Float 。这就是他们所说的“b”是由“a”唯一确定的意思。这扩展到任意数量的类型参数。需要它的原因是 1. 类型推断 2. 有时您想要这样的约束。

FD 的替代方案是类型族扩展,但并非适用于所有 FD 情况。

于 2010-11-25T15:17:25.617 回答