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 |
Console.WriteLine(format(parse("AF3D",16),3));
No comments:
Post a Comment