Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional Dependency in Haskell

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

like image 550
aXqd Avatar asked Nov 25 '10 14:11

aXqd


1 Answers

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.

like image 141
snk_kid Avatar answered Sep 21 '22 17:09

snk_kid