Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 7th, 2012  |  syntax: None  |  size: 1.36 KB  |  hits: 17  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. //  We're using this array to play with:
  2. NSArray* sample = [NSArray arrayWithObjects:@"foo",
  3.                                             @"bar",
  4.                                             @"baz",
  5.                                             @"teapot",
  6.                                             nil];
  7.  
  8.  
  9. //  Shall we map them so f(x) -> "SOMETHING#{x}"?
  10. NSArray* mapped = [sample mapWithBlock:^id(id obj) {
  11.     return [NSString stringWithFormat:@"SOMETHING%@", obj];
  12. }];
  13.  
  14.  
  15. // Let's map x with its index
  16. NSArray* mappedIndex = [sample mapWithIndexedBlock:
  17.   ^id(NSUInteger idx, id obj) {
  18.       return [NSString stringWithFormat:@"%@ AT INDEX %lu",
  19.                                         obj,
  20.                                         idx];
  21. }];
  22.  
  23.  
  24. //  How about reducing it?
  25. id reduced = [sample reduceWithBlock:^id(id memo, id obj) {
  26.     return [NSString stringWithFormat:@"%@-%@", memo, obj];
  27. } andAccumulator:@""];
  28.  
  29.  
  30. //  But we don't like teapots; let's remove them
  31. BOOL (^discriminator)(id obj) = ^(id obj) {
  32.   return [obj isEqual:@"teapot"];
  33. };
  34.  
  35. NSArray* teapotFree = [sample removeWithPredicate:
  36.                               discriminator];
  37.  
  38.  
  39. //  Even better, let's segregate them
  40. NSArray* segregated = [sample partitionWithBlock:
  41.                               discriminator];
  42.  
  43.  
  44. //  Now let's break *sample up into
  45. //  an array of 2-element NSArrays
  46. NSArray* chunked = [sample splitWithSize:2];