Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add "map" to NSDictionary

If you send the map: message to a dictionary and it will apply the provided
callable to each value and return another dictionary with the results set for
the corresponding keys.

E.g.:

    % (set origin (dict "alpha" 10 "bravo" 20))
    <__NSDictionaryM:7f9224202c50>
    % (set destination (origin map: (do (x y) (+ 1 y))))
    <__NSDictionaryM:7f9224202f40>
    % (destination "bravo")
    21
  • Loading branch information...
commit a8bd2e9e6b7af546d4003fa30ac72d0fb2f2f5d8 1 parent 68130d3
@andrewschleifer andrewschleifer authored committed
Showing with 26 additions and 0 deletions.
  1. +18 −0 objc/Nu.m
  2. +8 −0 test/test_dictionary.nu
View
18 objc/Nu.m
@@ -4378,6 +4378,24 @@ - (id) each:(id) block
return self;
}
+- (NSDictionary *) map: (id) callable
+{
+ NSMutableDictionary *results = [NSMutableDictionary dictionary];
+ id args = [[NuCell alloc] init];
+ if ([callable respondsToSelector:@selector(evalWithArguments:context:)]) {
+ NSEnumerator *enumerator = [self keyEnumerator];
+ id object;
+ while ((object = [enumerator nextObject])) {
+ [args setCar:object];
+ [args setCdr:[[[NuCell alloc] init] autorelease]];
+ [[args cdr] setCar:[self objectForKey:object]];
+ [results setObject:[callable evalWithArguments:args context:nil] forKey:object];
+ }
+ }
+ [args release];
+ return results;
+}
+
@end
@implementation NSMutableDictionary(Nu)
View
8 test/test_dictionary.nu
@@ -50,6 +50,14 @@
(if (eq v 3) (continue))
(set count (+ count 1))))
(assert_equal (- (d count) 1) count))
+
+ (- (id) testMap is
+ (set d (dict one:1 two:2 three:3 four:4))
+ (set o (d map:(do (k v) (+ 1 v))))
+ (assert_equal (d count) (o count))
+ (d each:
+ (do (k v)
+ (assert_equal (+ 1 v) (o k)))))
(- (id) testLookupWithDefault is
(set d (dict "one" 1 two:2))
Please sign in to comment.
Something went wrong with that request. Please try again.