Really silly things to do with C# expression trees


As you may remember from my last post I’m current reading Structure and Interpretation of Computer Programs as part of a study group we started during Pablo’s Fiesta.

I continue to find Lisp to be a fascinating language especially this really interesting piece of code.

Ok so what’s going on here?

  • if b > 0
    • return +
  • else
    • return –

In my previous post I demonstrated how you might implement this in javascript. Well I found it so interesting that I decided to find out if I could do it in C# as well. The following is my attempt at trying to return the + or – symbol from an if statement.

“Why would you write it this way when (insert code here) works better?”

Shut up troll! I’m not telling anybody to go off and write their code in expression trees when the following code is clear the correct why to write it.

See that’s way easier, but this isn’t a post about smart things to do with expression trees now is it?

Let’s up the silliness some more and make it an extension method just for fun.

I was having so much fun with this that I even roped some of my teammates in on it. Heres Chad Myers solution.

So I think its cool that you can kind of return + or – from an if statement, but what started as a fun little exercise turned into an amazing adventure into learning expression trees.

So as my final brain beating exercise I tried make this into a Func<int,int,int> completely build using expression trees.

So here’s a little challenge. In the comment section I invite you to completely school me in the ways of Expression Trees. Try and come up with a way more awesome version of a_plus_abs_b using expression trees or IL or whatever awesome sauce is in the .NET framework that I’m not aware of.

Herp Derp,

-Ryan

TIL everything in Lisp is a function