Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is no something like IMonad<T> in upcoming .NET 4.0

Tags:

c#

.net

monads

... with all those new (and not so new if we count IEnumerable) monad-related stuff?

interface IMonad<T>
{
 SelectMany/Bind();
 Return/Unit();
}

That would allow to write functions that operate on any monadic type. Or it's not so critical?

like image 963
UserControl Avatar asked Nov 10 '09 17:11

UserControl


1 Answers

Think about what the signature for IMonad<T>'s methods would have to be. In Haskell the Monad typeclass is defined as

class Monad m where
  (>>=) :: m a -> (a -> m b) -> m b
  return :: a -> m a

It's tricky to translate this directly to a C# interface because you need to be able to reference the specific implementing subtype ("m a" or ISpecificMonad<a>) within the definition of the general IMonad interface. OK, instead of trying to have (for example) IEnumerable<T> implement IMonad<T> directly, we'll try factoring the IMonad implementation out into a separate object which can be passed, along with the specific monad type instance, to whatever needs to treat it as a monad (this is "dictionary-passing style"). This will be IMonad<TMonad> and TMonad here will be not the T in IEnumerable<T>, but IEnumerable<T> itself. But wait -- this can't work either, because the signature of Return<T> for example has to get us from any type T to a TMonad<T>, for any TMonad<>. IMonad would have to be defined as something like

interface IMonad<TMonad<>> {

    TMonad<T> Unit<T>(T x);
    TMonad<U> SelectMany<T, U>(TMonad<T> x, Func<T, TMonad<U>> f);
}

using a hypothetical C# feature that would allow us to use type constructors (like TMonad<>) as generic type parameters. But of course C# does not have this feature (higher-kinded polymorphism). You can reify type constructors at runtime (typeof(IEnumerable<>)) but can't refer to them in type signatures without giving them parameters. So besides the -100 points thing, implementing this "properly" would require not just adding another ordinary interface definition, but deep additions to the type system.

That's why the ability to have query comprehensions over your own types is kind of hacked on (they just "magically" work if the right magic method names with the right signatures are there) instead of using the interface mechanism etc.

like image 190
Max Strini Avatar answered Nov 13 '22 21:11

Max Strini