You are viewing contextfree

Context-free journal

Recent Entries

11/15/09 08:51 pm - Why there is no general IMonad interface in the .NET framework

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.

Technorati Tags: monads,c#,.net,programming

4/19/09 06:39 am - 100%

I’m ready for an extended episode of controlled mania.  I’m going to push everything to or past its tolerance and I’m not afraid of breakage.

Powered by