8

What is the motivation of having functional dependencies in Haskell ?

One example of a functional dependency:

class (Monad m) => MonadSupply s m | m -> s where
  next :: m (Maybe s)

It is stated in the RWH book, that functional dependency helps the type checker. How does it actually help ?

Also, this piece of code actually compiles:

class (Monad m) => MonadSupply s m where
      next :: m (Maybe s)

But I guess, it will produce an runtime error.

Sibi
  • 47,472
  • 16
  • 95
  • 163

1 Answers1

8

It's perfectly fine to write code not using functional dependencies, it's just a pain to use since the inference sucks.

Basically without FDs, the function get :: MonadState m s => m s will have to figure out m and s independently. Usually m is quite easily inferred, but often s would require an explicit annotation.

Moreover, this is much more general than we need, so instead we can restrict our typechecker to say "For m, there is exactly 1 s", this way, once m is inferred, s is obvious to the type inference algorithm

daniel gratzer
  • 52,833
  • 11
  • 94
  • 134
  • I cannot understand how `For m, there is exactly 1 s`. If we tell, for `m` there is exactly one `s`, then why not write them as `MonadSupply m m` ? (I know that I'm sounding crazy :) ) – Sibi Dec 11 '13 at 18:24
  • @Sibi Because `s` is usually different, for example with `MonadState`, we have `StateT s` and `s`, clearly for all `StateT s` we really just want to use `s`. – daniel gratzer Dec 11 '13 at 18:26
  • Any given "supply monad" will typically only supply one type! For example if you have `m = MySpecialSupplyMonad s` that supplies values of type `s` then you know from the type "`MySpecialSupplyMonad s`" the supply type by just reading the type argument "`s`". Thus `s` can be said to functionally depend on `m`. – Tom Ellis Dec 11 '13 at 18:27
  • I think the type signature should look like this: `get :: MonadState s m => m s` ? – Sibi Dec 11 '13 at 18:31
  • @jozefg, thanks for your effort. But I'm still not able to grasp it. I have asked a new followup question. – Sibi Dec 11 '13 at 18:55
  • sounds more like a Sigma type rather than a (functionally) dependent type. (the difference being that (functionally) dependent type finds a type B for any type A; whereas Sigma is a evidence of existence of B for some A) – Sassa NF Dec 11 '13 at 20:27