Repository navigation
Description
tl;dr
Haskell has monads
Monads are like bacon
C# needs bacon
Introduction
I have a mad craving for higher kinded polymorphism in C#.
And I have no blog to call my own, so here's an essay on this stuff.
That's a fancy name with a lot of crazy type theory and papers behind it, but if you have an understanding of how generic types work in C#, the concept is not terribly hard to understand.
What C# with a taste of bacon would look like
public static T<A> To<T, A>(this IEnumerable<A> xs)
where T : <>, new(), ICollection<>
{
var ta = new T<A>();
foreach(var x in xs) {
ta.Add(x);
}
return ta;
}
...
{
var data = Enumerable.Range(0, 20);
var set = data.To<HashSet<>, int>(); // sorcery!
var linkedList = data.To<LinkedList<>, int>();
var list = data.To<List<>, int>();
}What is going on here?
where T : <>, // 1
new(), // 2
ICollection<> // 3- T is constrained to be a generic type definition with one type parameter.
- In CLR lingo: T is a generic type of arity 1
- In type theory lingo: T is a type constructor of kind
* -> *
- Also it should have a default constructor
- And it should implement
ICollection<>(meaningfor each type X, T<X> implements ICollection<X>)
Using this you could convert an IEnumerable<T> to any other type that is a collection.
Even all the ones you have never thought about, including the weird ones from libraries which do not get a whole lot of support because nobody uses them (except of course you).
Like HashSet (such a weird collection) or LinkedList (you would need to be crazy).
They are fine citizens of System.Collections.Generic and very useful, yet they don't get the love they deserve, because they are not as famous as List<> and implementing To...() methods in Linq for all of them would be a painful task.
However, with higher kinded polymorphism, they could all get a general concise implementation.
Where's the rest of that bacon?
That general conversion function is just the tip of the iceberg.
You can do all kinds of crazy transformations with higher kinded polymorphism.
And since it allows for such lovely abstractions you only have to implement them once.
Or better yet: Somebody else implements them in a NuGet package and you don't need to care.
Composition over coding.
Haskell? Is that a dog's name?
That NuGet package could be called something neat and concise like, say, Prelude. Yes, what a fine name!
There are some other party poopers, but the lack of Higher Kinded Polymorphism is the biggest road block in stealing all the juicy bacon from the Haskell community.
You know how Linq is awesome?
Do you also know how Linq is an implementation of the List Monad? (kind of)
Well, there are lots of more Monads in Prelude and most of them are awesome.
And currently a bitch to implement in C#.
Plus, HKP would allow to abstract on the concept of Monads!
And on concepts like Tuples (never heard of them), Functors (not what you're thinking), Arrows, Categories and all the crazy math that comes with them.
I've put together a gist of how wonderful this would be in combination with some other features for implementing Maybe.
I don't know what you're talking about, but it sounds expensive
Let's first look at a summary of the benefits that HKP would bring to C#
- This feature would make C# the most relevant functional programming language with sub-typing and strong static type checking
- A natural extension to the work done by the Linq team
- A natural extension to generics
- Much more natural porting of Haskell code (think about it: years upon years of research on bacon finally in a consumable form)
- A real implementation of the Maybe monad (about time)
- More expressiveness without sacrificing static typing
- HKPs allow something kind of Meta-programming without the nonsense. Whoever used C++ before knows how easily template programming becomes a nightmare. On the other hand, Haskell programmers are delighted by their juicy type system.
- Have I mentioned bacon?
Now let's talk about work:
- Before anything else, a proper implementation would require CLR support
- That would be quite involved, but not impossible. Also I believe it can be implemented as a strict extension to the current metadata without breaking existing libraries
- As a consequence, the F# crowd would benefit from this. I bet they are overjoyed to hear about bacon
- As another consequence, implementing Haskell on top of .Net would be much less of a pain
- C# Syntax
- In C# we can already refer to generic type definitions in
typeof()as intypeof(IDictionary<,>) - I think the
where T : <,>clause seems neat, but is probably not powerful enough (no way to constrain variance on T's parameters or 'swap' parameters for implementations)- maybe more like
where T<,> : <U, X>, IDictionary<X, U> - or rather
void Foo<A<B, C>, D>() where A<B, C> : IDictionary<C, B> where B : class
- maybe more like
- Well, the syntax needs work.
- In C# we can already refer to generic type definitions in
- Type checking
- it's not work if it's fun
But I'm a vegetarian
Think of Bacon as an abstract higher kinded type class with non-carnivorous implementations
Activity
VSadov commentedon Apr 23, 2015
There is an obvious issue with CLR not supporting higher-kinded types.
Some languages (Scala, F*) seem to be able to get around such limitations of underlying runtimes, but I do not know how well that works in practice.
@MadsTorgersen if not already there, higher kinded generics may need to be added to the list of possible future directions. Perhaps next to the Meta-programming :-).
diab0l commentedon Apr 24, 2015
From what I've seen on UserVoice and SO, there's encodings to do this stuff in F# using their inlining system.
But these encodings tend to be ugly, complex and compromising.
That definitely doesn't sound like something I want for C#.
It's also worth noting that the feature request has been rejected for F#, since it would require CLR support, it's costs outweigh it's benefits, etc., however that was before Core was open sourced and all this crazy open development started
GSPP commentedon Apr 29, 2015
@diab0l can you give more examples for what this would be good for? I always wondered what practical things you can do with higher kinded types.
For C# 6 they are not going to touch the CLR but there are other potential changes queued up (e.g. structural types and default implementations for interface methods). Maybe C# 7 can batch all of them into a new incompatible runtime.
isaacabraham commentedon May 2, 2015
@diab0l I don't think it's been rejected from F# because of lack of CLR support - I believe it could be done in a type erased style - it's simply not high up enough the feature list on uservoice.
I've also been hearing people in the F# community asking for GADTs first.
diab0l commentedon May 3, 2015
@isaacabraham Of course it could be implemented type-erased style, but that's an unpleasant can of worms.
If it were implemented like C++ templates, it would be a source level feature, meaning you can't have higher kinded polymorphic methods in assemblies. I think we can reach consensus that such a feature would only pollute the language.
If it were implemented like Java generics, it would lead to all sorts of nonsense. For example you couldn't do
typeof(M<>)inside the hkpm, since the type has been erased.So to implement this feature in a reusable way, there would at least need to be a way for the C# compiler to
Now since it has to happen at assembly level, that would essentially be a language-agnostic extension to the CLR's common type system.
And since the extra information would need to be encoded, it wouldn't be type erased at all, it would be reified, albeit in an ugly hack.
If we are going to extend the CLR's common type system with some cool feature anyway, then I would suggest we do it right: by adding it as a first-level feature to the standard and implementing it right instead of via (clever or not) ugly hacks.
diab0l commentedon May 3, 2015
@GSPP To be frank: I can't give you a whole lot of examples.
Until recently I just haven't given it any thought.
However, what I can tell you is that, as an abstraction feature which abstracts over abstract data structures it would primarily allow us to write some neat libraries.
Also, in Haskell it's used quite natural as part of every day programming for everything, so it allows for a different style in coding.
The best example I can currently come up with is abstracting over the Linq Zoo.
Consider you write a function which only relies on the shared semantics of
Linq-to-Objects(IEnumerable<>),Database Linq(IQueryable<>),PLinq(IParallelEnumerable<>),Reactive extensions(IObservable<>), whereverIQobservable<>lives and whichever other crazy Linq-style APIs everybody whips up.The only difference in the shared methods of these APIs (
Select(),First(), ...) isa) the data type they operate on (
IEnumerable<>,IQueryable<>, ...) andb) whether they straight up take
Func<>orExpression<Func<>>as arguments.We cannot currently abstract over a) or b) :(
Currently, as a library author who intends to write a method which works on either of these APIs, you would have to write your function each time for each API (without casting to
IEnumerable<>which forces a query to lose it's semantics, for example), even if your function does not care whether it queries anIEnumerable<>or anIParallelEnumerable<>or even anIQueryable<>.With the introduction of HKPMs, and a retrofitted static interface
ILinq<>for Linq implementations, you could write your awesome function once and it would work not only on these 5 Linq implementations, but on every future implementation as well.diab0l commentedon May 3, 2015
Please do not understand me wrong.
I am well aware that implementing this feature is going to be a big undertaking and not going to happen anytime soon, if at all.
At least not until the CLR ports have become stable and established.
Also, it's not clear whether higher kinded polymorphism would be a good fit for C#.
Maybe there's some better way to raise the bar on abstraction.
What I think is clear is that C# and the CLR have incorporated features from functional languages with great success and the trend for using C# as a functional language is strong.
Having all this in mind, I think it's worthwhile to explore how C# would benefit from first-level support for Higher Kinded Polymorphism and what such a syntax would be like.
Also I think that, along with related issues it raises the question: Should the common type system as a one-size-fits-all solution be all that common?
dzmitry-lahoda commentedon May 4, 2015
There is the example for HKT in C# http://www.sparxeng.com/blog/software/an-example-of-what-higher-kinded-types-could-make-possible-in-c.
MI3Guy commentedon May 11, 2015
Another advantage would be the ability to use value type collections (e.g. ImmutableArray) without boxing them or writing a method that uses that specific collection.
DrPizza commentedon May 15, 2015
Template template parameters are a good fit for C++, so it's natural enough that generic generic parameters would be a good fit for C#. Being able to make Linq methods independent of concrete classes seems nice enough.
gafter commentedon Sep 4, 2015
@TonyValenti Please suggest that in a new issue.
aluanhaddad commentedon Sep 17, 2015
I would love to see this addition if some future version of the framework enables it.
16 remaining items
diab0l commentedon Sep 28, 2016
I would like to add some more clarification, especially since what I originally wrote may not be clear enough for people unfamiliar with higher kinded types.
So here's some theory. Somebody correct me if I'm wrong.
Proper Types
Proper types are those inhabited by values which are not types themselves.
Examples are
int,bool,stringand any other value (struct) or reference type (class).Generic types closed over all their type arguments (such as
List<int>orKeyValuePair<string, int>) are also proper types.Kinds
Kinds are a formalization for type-level functions.
There's
*which reads as type, which is no coincidence, because all proper types are of kind*.There's also the operator
->which allows us to create kinds like* -> *which is a type function taking a proper type as parameter and returning a proper type as result. (Examples:List<>andSet<>)Such type functions are also called type constructors, since you give them some parameters and they 'construct' a type for you.
In other words, applying the proper type
intto the type constructorList<>yields the proper typeList<int>.Generic types
So,
* -> *is the kind of generic types with arity 1 (List<>,Set<>, etc.),* -> * -> *is the kind of generic types with arity 2 (Tuple<,>,KeyValuePair<,>,Dictionary<,>).and so on.
These are things we can already express within C# and the CLR and we call them generic types.
To slightly complicate the picture, we also have generic methods which are in a sense function constructors. They are like type constructors, except they do not return a proper type, but instead a proper function.
Higher kinded types
What we cannot express are higher-kinded types.
An example would be
(* -> *) -> * -> *, which is a type function taking a type constructor and a proper type as argument and returning a type.Here's what the signature could look like in C#:
Another useful kind would be
(* -> *) -> (* -> *)which could be used to have a general mapping from one type constructor to another. To make this meaningful, we would need to know something about the types constructors and the way to do that would be constraints.We can currently neither have a type argument which is a type constructor itself and even if we could, we couldn't meaningfully constrain it.
There are other things we cannot express. For example you can't have a variable of type
Action<>or of typeFunc<,>, so you can have generic methods, but not generic lambda methods.Tl;dr;
To sum it up, today we can range over the
UinT<U>.What I want is to be able to range over the
Tin a meaningful way (with constraints).Alxandr commentedon Sep 28, 2016
While I (think) I perfectly understood all of that (I've done haskell), I think the
* -> *and(* -> *) -> *annotation is confusing for people who are not used to functional programming languages. I remember starting in F# and readingint -> int -> intis confusing if you're not used to it.To translate the same into something akin to TypeScript (C# doesn't really have a
funcannotation) it could look something like this:whereas what we would like to express is
Not sure about the syntax, but I do believe we might want to try to write things in a format thats more similar to what most C# devs are used to (at least while we're in the roslyn repo).
Or if an interface would help:
Syntax is obviously something that should be discussed, and I don't know what works best, but personally I think figuring out how things should work on the CLR level first is probably the best idea. Also, I haven't written C# in a while, so apologies if there are any glaring errors in my snippets :)
diab0l commentedon Sep 29, 2016
@Alxandr
I do agree completely and gosh, I hope this stuff eventually makes it's way into typescript.
The interface is probably the best analogy.
There are also proposals for 'static interfaces' which would allow for similar abstractions.
toburger commentedon Oct 12, 2016
it seems that there's a light at the end of the tunnel: https://www.youtube.com/watch?v=hK5GJoH4PlI
gusty commentedon Oct 12, 2016
@toburger That technique doesn't cover Higher Order Kinds. It allows you to define 'first-order-kind typeclasses' like
Monoidand generalize over numeric types, but in order to be able to represent functors, applicatives or monads you still need to do something at the CLR level.Opiumtm commentedon Oct 12, 2016
Your example is perfectly possible using current C# syntax
sideeffffect commentedon Oct 12, 2016
if you haven't heard, there's this for HKT in F#
https://github.com/palladin/Higher
now I'm wondering, that this should also work in C#
of course, this is more like a hack/workaround, but until we have a proper implementation of HKT in the language(s) and/or CLR, this could aleviate some problems
Opiumtm commentedon Oct 12, 2016
And from mentioned above article.
Example:
Exact generic logic to example above:
So, T<?> seems to be just short-hand for existing type constraints that require to explicitly declare type arguments of TItem1, TItem2 item types and TArg1, TArg2 enumerables.
And LINQable<?> here isn't possible and not a case of higher-order polymorphism because LINQ queries use structural typing (LINQable is every type which provide standard Where(), Select() and so on methods - it isn't bound to exact interfaces, it use structural typing instead)
So, C# should officially support some forms of structural typing as it already support structural typing for awaitables and LINQ-ables and don't support general-purpose structural typing
gabomgp commentedon Nov 10, 2016
@Opiumtm I think structural typing is a very big change for C#, maybe something similar to traits/type classes/protocols would be better. Traits in Rust are very similiar to extension methods, but think in interfaces than extends the behavior instead of methods.
dzmitry-lahoda commentedon Nov 17, 2016
I am not sure, but seems case like next could also get use of HKT.
Given next usage of CsvHelper:
And call:
With HKT is seems would be next:
With HKT we will get less code to type when method is called - only 1 name of class, instead of 2:
And I do not understand Microsoft CodeAnalysis(CA) errors I see - may be will have no reason for these given HKT in place:
Does CA suggest to make HKT into C# for proper design?
bondsbw commentedon Dec 14, 2016
The following
DateTimeCollectiontype appears to satisfy the requirements forTin the original example:But
DateTimeCollectionhas a type parameter constraint, so it would need to fail when that constraint is not satisfied:The primary location of the problem is in the return type:
Because there is no guarantee that
Ais allowed as a parameter ofT. So that should be specified in the type constraints forT:bondsbw commentedon Dec 14, 2016
Perhaps the type constraint for
ICollection<>needs to be specified as well:Otherwise wouldn't this line fail?
alexandru commentedon Feb 2, 2017
@aluanhaddad OOP subtyping / overloading doesn't help with the most useful operation of all, which is
bind/flatMap(I think it's calledSelectManyin .NET) because in OOP you have co/contra-variance as a natural effect of subtyping + generics and function parameters are contra-variant, which means you'll lose type info.In practice this means you can't describe such operations by means of inheritance (and please excuse the Scala syntax, I'm just a newbie in F#):
Well, in Scala you can describe
flatMapwith inheritance, but then you need another feature in the type-system, called F-bounded types. Scala can do that too, but this is another feature you don't see in other OOP languages, since this also needs higher-kinded types to be useful, (see article with details):Looks ugly but it is very useful for sharing implementation while not downgrading to the super-type in all those operations.
gafter commentedon Mar 24, 2017
Issue moved to dotnet/csharplang #339 via ZenHub