简体   繁体   中英

Understanding Type Classes, Scala implicit and C#

I read this blog post by Joe Duffy about Haskell type classes and C# interfaces.

I'm trying to understand what could have enabled c# to have type classes, and I wonder whether a feature like scala's implicits could solve it?

having this kind of feature would enable writing something like this:

public interface IReducableOf<T>
{
   T Append(T a, T b);
   T Empty();
}

public T Reduce(this IEnumerable<T> vals, **implicit** IReducerOf<T> reducer )
{
  Enumerable.Aggregate(vals, reducer.Append);
}

making sure that we have in our context an implementation of IReducerOf<T> than the compiler could "just" pick the reducer and use it to execute the code.

of course, this code cannot compile.

But my questions are:

  1. Can this enable implementing type classes?

  2. Is this similar to what is happening in scala?

I'm asking this for general understanding and not for a particular problem.

UPDATE

I've encountered this GitHub repo on possible implementation of type classes in c#

Yes, this is exactly how type classes are implemented in Scala. It is a general design principle in Scala to add general and re-usable features to the language that can be used to implement higher-level constructs as library constructs, if at all possible. In this particular case, type classes can be implemented using objects and implicits, but both objects and implicits have uses beyond merely implementing type classes, so it makes more sense to include those more general building blocks in the language and allow the users to build higher-level constructs (like type classes) on top.

The canonical paper on implementing type classes as objects and implicits is the aptly named Type Classes as Objects and Implicits by Bruno C. d. S. Oliveira, Adriaan Moors, and Martin Odersky . There's a nice discussion of this paper on Lambda-the-Ultimate .

Note that just adding implicits to the language would probably not be enough. You could implement type classes that way, but a lot of "interesting" type classes (such as Monad ) cannot be expresses in C♯: Monad is higher-kinded, but C♯'s type system is not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM