Tuesday, August 07, 2012

Recursive lambdas

More and more programming languages supports a functional approach to programming. the functional approach gives a more compact syntax that for some people will be easier to read because everything can be kept together.

In C#, lambda expressions take us closer towards functional programming. An important concept of functional programming is recursitivity which in many cases can replace loops.

I pulled up my old base conversion algoritm and gave it a try. Basically it takes an integer and returns a string respresented in a base of your choice.

Integers to Text

The variable chars contains the characters used in the output. For a conversion to base 16 (hex) the first 16 are used etc..
C# doesn't let you reference something that is defined in the same line, so the signature of the lambda is defined in the previous line. The actual conversion is all written in one line of code and I'll let you decipher it yourselfes. Because of the recursion, no loop is required. It will basically calls itself for every character to be output. As C# doesn't support tail recursion (this is not completely true, but I won't count on it anyway), recursive code in C# has a limit to how many times a method can call itself.

I also did one that goes the other way.

Text to Integer
What i have now is two methods so that I can convert from any base (limited to the length of the charset used) to any other base. this is how i convert a hex number into base 3.


No comments:

Post a Comment