4 ms·
> No, the developers do, because the language is not expressive enough to express generic pieces of code without losing type info, so you need reflection for co
by louthy 8y ago
> No, the developers do, because the language is not expressive enough to express generic pieces of code without losing type info, so you need reflection for constraints (e.g. "new T" or "instanceOf" checks) and runtime guards for downcasting.
The type system is totally capable of it. The language doesn't make it easy, but the code below is essentially type-classes and class-instances if you squint. It's something the C# team are looking into now anyway, but the main point is the type system doesn't preclude it.
public interface Newable<A>
{
T New();
}
public struct NewableThing : Newable<Thing>
{
Thing New() => new Thing();
}
public class Foo
{
public A Bar<NewableA, A>() where NewableA : struct, Newable<A> =>
default(NewableA).New();
}
> Classic example: express a "sum" function that works on any Array<A>.
public interface Num<A>
{
A Zero();
A Add(A x, A y);
}
public struct NumInt : Num<int>
{
int Zero() => 0;
int Add(int x, int y) => x + y;
}
public struct NumFloat : Num<float>
{
float Zero() => 0;
float Add(float x, float y) => x + y;
}
public static A Sum<NumA, A>(A[] xs) where NumA : struct, Num<A> =>
xs.Fold(default(NumA).Zero(), (s, x) => default(NumA).Add(s, x));
int sumInt = Sum<NumInt, int>(new [] {1,2,3,4});
int sumFlt = Sum<NumFloat, float>(new [] {1.0,2.0,3.0,4.0});
> Of course, but that too is part of the problem.
That's a very hand wavey statement. It's the goal of all staticly typed compilers to resolve to concrete types at compile time. How is part of any problem? The CLR has the capability to generate new concrete types from generic types at runtime if required, but obviously tries to do as much of that work up front at compile time.