Tuesday, February 9, 2016

Using C# Expression Trees for Compiling Run-time Code

This is a follow up on the Genetic Algorithms Used to Search Solution Space post several years ago.

I just became aware of C# Expression trees.  The common application is for SQL database queries.

More exciting: Expression trees can also be used to compile arbitrary code, the first step in implementing the genetic algorithms as described in the post above.

For excellent tutorials on expression trees, see Jamie King's C# Expression Trees youtube video playlist.  If you like his videos, consider supporting him in some way.


Consider the following code for Unity:

using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection.Emit;

public class Test : MonoBehaviour {

// Use this for initialization
void Start () {
int myC =

UnityEngine.Random.Range(0,30);


int myTI =

UnityEngine.Random.Range(-5,50);


ConstantExpression cE =

Expression.Constant( myC, typeof(int) );


ParameterExpression iP =

Expression.Parameter( typeof(int), "i" );


List<BinaryExpression> exps =

new List<BinaryExpression>(3) 
Expression.GreaterThan( iP, cE ), 
Expression.LessThan( iP, cE ), 
Expression.Equal( iP, cE ) 
};


int indexExp =

UnityEngine.Random.Range(0, exps.Count );


BinaryExpression myExp =

exps[indexExp];


Expression<Func<int, bool>> testRand =

Expression.Lambda<Func<int, bool>>( myExp, iP );


Func<int, bool> dele =

testRand.Compile();


Debug.Log ( "myC="+myC);
Debug.Log ( "myTI="+myTI);
Debug.Log ( "myTI " + myExp.NodeType + " myC = " + dele(myTI) );


}

}



Attach this script to an object in Unity (I used the main camera) and run, and you should get output something like this over several runs:

myC=17
myTI=-4
myTI LessThan myC = True

myC=20
myTI=9
myTI GreaterThan myC = False

So what is this code doing?  It's generating a random BinaryExpression at runtime, then compiling and running the expression at runtime.

When I found this I was overjoyed!  This is a relatively straightforward way to compile algorithms at runtime to search any random algorithm space.

No comments:

Post a Comment