Hacking C#’s Lambda Expressions Into Hash Rockets

c# loves RubyAs I move between C# and Ruby, I have found my brain’s internal syntax parser always needing to switch gears and repurpose its understanding of Fat Arrow, =>. In Ruby, it provides a visually salient means of expressing key => value pairing within a Hash. C# on the other hand uses it to indicate the opening of a lambda expression’s body block, x => x + y. Its notable that in other languages, such as Coffee Script, it has a similar meaning. In any case, the lines sometimes blur as I’m dreaming up new ways to make C# look and behave more like my favorite dynamic language.

In this post, I’m going to show you how to repurpose C#’s lambda expression syntax for creating key,value pairs.  My goal is be able create nestable enumerable graph structures with a syntax like this:

var rockets = __.Rocketize(
                               foo => "asdf",
                               bar => 42,
                               biz => new Business{ Name = "AMD" },
                               now => DateTime.Now,
                               fun => new Func(() => return new Awesome(source: "Joel Holder")),
                               sub => __.Rocketize(a => 'b',
                                                   c => 'd',
                                                   e => 'f'),
                               xml => File.ReadAllText(@"data.xml"),
                               web => new Uri("https://uberpwn.wordpress.com/"),
                               ___ => typeof(__),
                               tru => (2*2+3*3)/(5*5) == 1,
                               etc => "..."
                          );

First we need a few functions that leverage the Expression API to provide a means of taking in a series of lambda expressions. Internally, we will convert each expression’s AST into a named key and value of Func<> that  returns an optional state object.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;

namespace HashRocket
{
    public class __
    {
        public static IEnumerable<KeyValuePair<object, Func<object, object>>> Rocketize(params Expression<Func<object, object>>[] exprs)
        {
            return exprs.Select(expr =>
            {
                var key = expr.Parameters.FirstOrDefault() != null
                            ? expr.Parameters.FirstOrDefault().Name
                            : DateTime.Now.Ticks.ToString();
                return Rocketize(key, expr).First();
            });
        }
        public static IEnumerable<KeyValuePair<object, Func<object, object>>> Rocketize(object key, params Expression<Func<object, object>>[] exprs)
        {
            return exprs.Select(expr =>
            {
                var fn = expr.Compile();
                return new KeyValuePair<object, Func<object, object>>(key, fn);
            });
        }
    }
}

Now that we have this in place, we can run a few tests to show off the behavior. Note that I’ve opted for IEnumerables of KeyValuePair instead of a Dictionary or Hashtable. This just a personal preference, in that I wanted to support multiple objects with the same key within the data structure.

using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace HashRocket.Tests
{
    [TestClass]
    public class Tests
    {
        [TestMethod]
        public void Can_Convert_Lambda_Into_Kvp()
        {
            //arrange
            var testInput = "asdf";

            //act
            var rocket = __.Rocketize(input => input).First();

            //assert
            Assert.IsTrue(rocket.Key.Equals("input"));
            Assert.IsTrue(rocket.Value(testInput).Equals("asdf"));
        }

        [TestMethod]
        public void Can_Convert_Multiple_Lambdas_Into_Multiple_Kvps()
        {
            //arrange
            var testInputs = new object[] {"asdf","zxcv",2};

            //act
            var rockets = __.Rocketize(foo => foo + "qwer0",
                                       bar => bar + "qwer1",
                                       biz => biz + "qwer2").ToList();

            //assert
            for (var i = 0; i < rockets.Count; i++)
            {
                Assert.IsTrue(rockets[i].Value(testInputs[i]).Equals(testInputs[i] + "qwer" + i));
            }
        }
}

What’s surprisingly cool about this approach is that it becomes very easy create configuration objects with lambda syntax that can be passed directly into objects for initialization. If you’re familiar with this pattern in Ruby or JavaScript, you’ll appreciate the power and elegance it also affords to C#. To better understand the benefits and potential tradeoffs to using this trick, see Jeremy Skinner’s article on the topic.

Namaste..

Extend Ruby Enumerables With An EachN Processor

Here’s a useful enhancement to arrays that allows you to process elements in a block n at a time. N is inferred by the arity of your block signature.

require 'enumerator'

module Enumerable
  def eachn(&block)
    n = block.arity
    each_slice(n) {|i| block.call(*i)}
  end
end

a = (1..10).to_a
a.eachn {|x,y,z| p [x,y,z]}

Namaste…

Sleek CLI wrappers around Ruby libs

When using Ruby’s splat operator for method invocation, eg. my_method(*my_array), it takes the array and blows it out into the parameters required to fill the method’s signature. This makes it super easy to call methods from classes via the command line, by simply passing the arguments (ARGV) to a Ruby command line app and then directly down into a Ruby class API. The key to my approach is to do this in a very DRY way with as little code as possible. Here’s how I do it.

First we’ll create a file called seeker.rb with a class a API that looks like this:

class Seeker
  def work_file(infile, outfile, suffix, delimeter)
    p "parameter 1: infile = #{infile}"
    p "parameter 2: outfile = #{outfile}"
    p "parameter 3: suffix = #{suffix}"
    p "parameter 4: delimeter = #{delimeter}"
    #do important stuff, etc..
  end
end

Now, we can create a generic wrapper script to drive it like this by doing the following. Create a file called just seeker. Make sure to chmod +x seeker. Add the following text:

#!/usr/bin/env ruby

require File.expand_path('seeker.rb', __FILE__)
Seeker.new.send(ARGV.shift.to_sym, *ARGV)

With this generic message passing script in place, we can call the API like this:

$./seeker work_file foo.txt bar.txt .com ,

Running this command, we get the following output:

parameter 1: infile = foo.txt
parameter 2: outfile = bar.txt
parameter 3: suffix = .com
parameter 4: delimeter = ,

The ease with which we’re able to pass input from the cli straight into our class API comes from the splat operator’s ability to turn an ordered set of cli args into Ruby method params. Notice that we chewed off ARGV[0] as the name of the method we wanted to run. Using the builtin “send” method, which sends a generic message to an instance of a Ruby class, we can invoke any method by simply specifying it as the first cli arg followed by the parameters to be passed into the method, which are just the subsequent cli args.

With a general purpose wrapper like this we can invoke any method on any target class with no additional code. This is a testament to the sheer goodness of Ruby.