Dynamic Linq Expressions and GADTs...new approach to the expression problem in C#

Joined
Jan 10, 2007
Messages
43,898
Location
In The Machine
Hi all,

I was watching the video of Anders Hejlsberg's talk at Lang.Net 2008. About 3/4 of the way through, he mentioned that you can actually compile Linq expressions at runtime, and this is part of the basis for dynamic C# features going forward. I had no idea that this sort of thing was enabled in 3.5...thought the only way to dynamic was through reflection or IL.

So, I've been playing around to understand the functionality, trying to address the expression problem for generalized algebraic data types (GADTs).

Let me know what you guys think of this kernel of an implementation:

namespace C9Question
{
*** public class TestGADT
*** {
******* public static void Main()
******* {
*********** Number n1 = 5;
*********** Number n2 = 4;
*********** Console.WriteLine(n1+n2);
*********** Console.Read();
******* }
*** }
***
*** public struct Number where T : struct
*** {
******* public T myNumber;
*******
******* public T Add(T a, T b)
******* {
*********** Func f = typeof(GADTHelper).GetFunc("Add");
*********** return f(a, b);
******* }

******* public static Number Add(Number a, Number b)
******* {
*********** Func f = typeof(GADTHelper).GetFunc("Add");
*********** return new Number() { myNumber = f(a.myNumber, b.myNumber) };
******* }

******* public static Number operator +(Number a, Number b){ return Add(a, b); }
******* public static implicit operator Number(T value) { return new Number() { myNumber = value }; }
******* public override string ToString() { return myNumber.ToString(); }
*******
*** *** private static class GADTHelper
******* {
*********** public static double Add(double myDouble, double myAddend) { return myDouble + myAddend; }
*********** public static float Add(float myDouble, float myAddend) { return myDouble + myAddend; }
*********** public static int Add(int myDouble, int myAddend) { return myDouble + myAddend; }
*********** public static long Add(long myDouble, long myAddend) { return myDouble + myAddend; }
******* }
*** }

*** public static class DynamicLinqExtensions
*** {
******* public static Func GetFunc(this Type t, string method)
******* {
*********** Type[] types = new Type[] { typeof(T1), typeof(T2) };
*********** ParameterExpression p1 = Expression.Parameter(types[0], "p1");
*********** ParameterExpression p2 = Expression.Parameter(types[1], "p2");
*********** Expression body = Expression.Call(t.GetMethod(method, types), p1, p2);
*********** Expression e = Expression.Lambda(body, p1, p2);
*********** return e.Compile();
******* }
*** }
}



More...

View All Our Microsoft Related Feeds
 
Back
Top