robb / Asterism

Asterism is yet another functional toolbelt for Objective-C. It tries to be typesafe and simple.
http://robb.github.io/Asterism/
MIT License
226 stars 12 forks source link

Add ASTChain #46

Open robb opened 10 years ago

robb commented 10 years ago

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…

felixvisee commented 10 years ago

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);
robb commented 10 years ago

That works already