Functional dependencies

From HaskellWiki

Functional dependencies are used to constrain the parameters of type classes. They let you state that in a multi-parameter type class, one of the parameters can be determined from the others, so that the parameter determined by the others can, for example, be the return type but none of the argument types of some of the methods.

1 Examples

Suppose you want to implement some code to perform simple linear algebra:

The functional dependency "container -> elem" promises that we won't declare multiple instances with the same "container" type.

instance Extract (a,b) a where
extract (x,_)= x

Because of the functional dependency we can't have the previous instance *and* this one:

-- instance Extract (a,b) b where ...

Because of the functional dependency we can say:

v = extract ('x',3)

and it will infer the type

v ::Char

Without the functional dependency, both instances above would be allowed, and the type of v would be potentially ambiguous. Even if only one instance is defined, the type system will not figure it out without the functional dependency.