Asterism icon indicating copy to clipboard operation
Asterism copied to clipboard

Add ASTChain

Open robb opened this issue 10 years ago • 2 comments

This adds ASTChain, a helper macro to reduce boilerplate in cases where intermediate results of a transformation would pollute the current scope.

E.g.

NSArray *messages = ASTPluck(tweets, @keypath(XYTweet.new, message));

NSArray *strings = ASTFilter(values, ^(id obj) {
    return [obj isKindOfClass:NSString.class];
});

NSArray *result = ASTMap(values, ^(NSString *string) {
    return string.resultString;
});

NSLog(@"%@", result);

could be replaced with

NSArray *result = ASTChain(
    ASTPluck(tweets, @keypath(XYTweet.new, message)),
    ASTFilter(_, ^(id obj) {
        return [obj isKindOfClass:NSString.class];
    }),
    ASTMap(_, ^(NSString *string) {
        return string.capitalizedString;
    })
);

NSLog(@"%@", result);

removing the need for temporary messages and strings variables.

I think it's worth pointing out that the _ variable contains the result and has the type of the previous expression. In the above example, this makes sure that the correct ASTMap version is picked (in this case the one for arrays).

Would love to hear some opinions on this, since it may just be a little to much macro-magic…

robb avatar May 22 '14 13:05 robb

Should be ok?! I'm wondering whether it would make (style-)sense to pass the initial value separately, giving all transformations the same form:

NSArray *result = ASTChain(tweets,
    ASTPluck(_, @keypath(XYTweet.new, message)),
    ASTFilter(_, ^(id obj) {
        return [obj isKindOfClass:NSString.class];
    }),
    ASTMap(_, ^(NSString *string) {
        return string.capitalizedString;
    })
);

NSLog(@"%@", result);

felixvisee avatar May 22 '14 22:05 felixvisee

That works already

robb avatar May 22 '14 22:05 robb