Functional languages often have Functor types/interfaces.
In .NET a Functor interface would be an Interface implementable by generic types (T<A>) that has a function called fmap that takes a function from the container type (A) to a different type (B) and returns an object with container type B.
For example a type List<A> would have a method List.fmap. The signature would be something like:
public List<B> fmap<B>(Func<A,B>);
Is it possible to create such an interface? Is it possible to do something similar? Are there any packages that provide an Interface like this and provide extension methods for obvious classes (List<T>, Dictionary<A,B>, Set<A>, etc.) ?
Update:
I know that IEnumerable objects almost do this. The key difference is that IEnumerable.Select returns an IEnumerable not the type of the implementer. For example, List.Select(A => B) returns IEnumerable not List. This shows why you can not implement IMappable in the obvious way for .NET, but is there a hack or extra type information you could use to effectively implement it?
Okay, based on the comment, I suspect the answer’s no – you’d need higher-order generic types. You’d want something like:
The problem is trying to express the idea that the implementation of the interface must also be generic in a particular way, and allow that generic relationship to be used in the rest of the interface. That’s not part of .NET generics, I’m afraid.
Joe Duffy has written about wishing for higher-order types before now – unfortunately I can’t tell whether or not that article is relevant, as I can’t get to it at the moment. (His blog server is somewhat temporamently, but the content is great 🙂
It’s not entirely clear, but it’s possible you’re just talking about LINQ to Objects, basically. For example:
You could write a more general purpose interface, e.g.
… but there’s no such interface actually implemented by
List<T>etc. LINQ to Objects works via extension methods instead.