Lambada in C#
Sriram Krishnan attempts to create lambada in C#, and James Robertson sneers at the attempt.
Peronally, I don't understand why she took the string approach even if she wanted to remain general. Delegates are perfectly possible to move a delegate around in a type-safe manner.
Here is a possible solution1, it works for both static and instance methods.
1: using System;
2: using System.Collections;
3:
4: namespace Lambada
5: {
6: class Mai2n
7: {
8: private static string[] words = {"dog","cat","mink"};
9: delegate void StringDelegate(string args);
10: delegate string RetStringDelegate(string args);
11: delegate void IntegerDelegate(int i);
12:
13: private static void PrintInt(int i)
14: {
15: Console.WriteLine("Integer: " +i);
16: }
17:
18: private static void PrintStr(string str)
19: {
20: Console.WriteLine(str);
21: }
22:
23: private static string Capitalize(string str)
24: {
25: if(!Char.IsUpper(str,0))
26: str = Char.ToUpper(str[0])+str.Substring(1);
27: return str;
28: }
29:
30: private int multiplyBy;
31: public void Multiply(int i)
32: {
33: Console.WriteLine("Multiply by "
+ multiplyBy +": " + i*multiplyBy);
34: }
35:
36: public static void Main(string[] args)
37: {
38: Mai2n m = new Mai2n();
39: m.multiplyBy = 2;
40: Map(new StringDelegate(PrintStr),words);
41: Map(new IntegerDelegate(PrintInt),new int[]
{1,3,5,7,11,13});
42: Map(new StringDelegate(PrintStr),
43: ReturningMap(new RetStringDelegate(Capitalize)
,words));
44: Map(new IntegerDelegate(m.Multiply),new int[]
{2,4,6,8,10});
45: }
46:
47: public static void Map(Delegate d, IList list)
48: {
49: foreach (object o in list)
50: {
51: d.DynamicInvoke(new object[]{o});
52: }
53: }
54:
55: public static IList ReturningMap(Delegate d, IList list)
56: {
57: ArrayList al = new ArrayList(list.Count);
58: object ret;
59: foreach(object o in list)
60: {
61: ret = d.DynamicInvoke(new object[]{o});
62: if(ret!=null)
63: al.Add(ret);
64: }
65: return al;
66: }
67: }
68: }
Here is the output of the above program:
dog
cat
mink
Integer: 1
Integer: 3
Integer: 5
Integer: 7
Integer: 11
Integer: 13
Dog
Cat
Mink
Multiply by 2: 4
Multiply by 2: 8
Multiply by 2: 12
Multiply by 2: 16
Multiply by 2: 20
1 Possible restrictions about no error checking, validation etc apply :-)
"A coat hanger is 44 inches long when straightened." -- Fact of lifes
"Quality assurance: A way to ensure you never deliver shoddy goods accidentally." -- Tech Support Slogan
"If you yelled for 8 years, 7 months and 6 days, you would have produced enough sound energy to heat one cup of coffee." -- Fact of lifes
Comments
Comment preview