コードを見て、非常によく似た2つの大きなブロックを見つけたとします。 実際、それらは同じで、ブロックの1つだけがスパゲッティを指し、2つ目はチョコレートムースを指します。
// - Main Console.WriteLine(“I’d like some Spaghetti!”); Console.WriteLine(“I’d like some Chocolate Moose!”);
C#, , - - , .
, :
public void SwedishChief(string food) { Console.WriteLine(string.Format(“I’d like some {0}!”, food)); } SwedishChief(“Spaghetti”); SwedishChief(“Chocolate Moose”);
, , , , - . , — , , = !
, , , BoomBoom, — PutInPot. , .
Console.WriteLine(“get the lobster”); PutInPot(“water”); PutInPot(“lobster”); Console.WriteLine(“get the chicken”); BoomBoom(“chicken”); BoomBoom(“coconut”);
, . , , .
// : // , // alert. public static T Alert<T>(T message) { Console.WriteLine(message.ToString()); return message; } public void Cook(string ingredientOne, string ingredientTwo, Action<string> function) { Console.WriteLine(string.Format("get the {0}",ingredientOne)); function(ingredientOne); function(ingredientTwo); } Cook(“lobster”, “water”, PutInPot); Cook(“chicken”, “coconut”, BoomBoom);
! .
?
… , PutInPot BoomBoom. (inline), - .
Cook("lobster", "water", x => Alert("pot " + x)); Cook("chicken", "coconut", x => Alert("boom " + x));
, . , , , Cook()…
“ ”, , , , - .
... var list = new List<int> { 1, 2, 3 }; for (var i = 0; i < list.Count; i++) { list[i] = list[i] * 2; } foreach (var el in list) { Alert(el.ToString()); } ...
- , , .
public static void Map<T>(Func<T, T> action, IList<T> list) { for (var i = 0; i < list.Count; i++) list[i] = action(list[i]); }
, :
... Map((x) => x * 2, list); Map(Alert, list); ...
, , - .
… Alert(Sum(list)); Alert(Join(new[] { "a", "b", "c" })); ... public static int Sum(IEnumerable<int> list) { var sum = 0; foreach (var el in list) sum += el; return sum; } public static string Join(IEnumerable<string> list) { var result = string.Empty; foreach (var el in list) result += el; return result; }
Sum Join , - , .
public static T Reduce<T>(Func<T, T, T> func, IEnumerable<T> list, T init) { var accumulator = init; foreach (var el in list) accumulator = func(accumulator, el); return accumulator; } public static int Sum(IEnumerable<int> list) { return Reduce((x, y) => x + y, list, 0); } public static string Join(IEnumerable<string> list) { return Reduce((a,b) => a + b, list, string.Empty); }
. , ( , -). , - .
Java , , . , , . , . , !
, , , - ?
, map. - , , . -, - , ? . , , , map !
, , , - . , , , . map , .
, map .
, , map reduce , , , -, , map reduce , , , , .
. , , , .
“ -, , Java”. MapReduce, Google . Map Reduce Lisp . MapReduce, , 6.001 , , , . , Google MapReduce, Microsoft, , Microsoft , , Google — Skynet^H^H^H^H^H^H — . , Microsoft , .
. , , , , , , . Google MapReduce, , - .
, , , . FORTRAN , , . , , , - . Java , . , Java — .
P.S. FORTRAN 27 . -, . , , GW-BASIC.