Y-Combinator in Objective-C

A GitHub user named Joshua Ballenco recently posted a project called y.h.
It’s an implementation of the Y-Combinator which is used in functional programming to achieve recursion using anonymous functions.
Apple is lucky to have talented people trying to make their language nicer to use.
Apple did well adding Blocks(closures) to Objective-C which slightly modernises the language. Unfortunately even with (because of?) Cocoa it’s not very expressive…

I mean look at this:

RecurBlock factorial = YComb((NSNumber *) ^(NSNumber *val) {
if([val compare: [NSNumber numberWithInt: 0]] == NSOrderedSame) {
return [NSNumber numberWithInt:1];
} else {
NSNumber *next_val = this_block([NSNumber numberWithInt:([val intValue] - 1)]);
return [NSNumber numberWithInt:([val intValue] * [next_val intValue])];
}
});

Could well be the least expressive implementation of a recursive factorial ever.
I’m not sure I know what to say…

Maybe MacRuby will save us all!

Tagged , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 180 other followers

%d bloggers like this: