The correspondence of Nu and Objective-C


Here’s a small example that implements the same method in Nu and in Objective-C. In this case, we’ll look at the method that allows us to index arrays with integers, which lets us do things like this:

[Oxygen:~/Desktop/Repositories/Nu] tim% nush
Nu Shell.
% (set a (array 'x 'y 'z))
<NSCFArray:361620>
% (a 1)
y

First, here is the Nu version:

(class NSArray   
     ;; When an unknown message is received by an array,
     ;; if it is an integer, treat it as a call to objectAtIndex:.
     (- (id) handleUnknownMessage:(id) method withContext:(id) context is
        (let ((m ((method car) evalWithContext:context)))
             (if (m isKindOfClass:NSNumber)
                 (then (if (and (< m (self count)) (>= m 0))
                           (then (self objectAtIndex:m))
                           (else nil)))
                 (else (super handleUnknownMessage:method
                              withContext:context))))))

Now here is the same method in Objective-C:

@implementation NSArray(Nu)

- (id) handleUnknownMessage:(NuCell *) method
       withContext:(NSMutableDictionary *) context
{
    id m = [[method car] evalWithContext:context];
    if ([m isKindOfClass:[NSNumber class]]) {
        int mm = [m intValue];
        if ((mm < [self count]) && (mm >= 0)) {
            return [self objectAtIndex:mm];
        }
        else {
            return nil;
        }
    }
    else {
        return [super handleUnknownMessage:method 
                      withContext:context];
    }
}
@end

What’s different? The Objective-C version is compiled and fast, the Nu version is interpreted and easy to write and test. I wrote the Nu version first, then wrote some tests, and much later (today) converted it to Objective-C in a few minutes. Since the Objective-C version could be tested with the same tests that verified the Nu one, I just had to rerun my existing tests - and now this change is good to go.