Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a version of the 'andand' monad for Objective-C?

I've recently started using Ick's 'andand' for Ruby so I can iterate through nested collections more easily than before.

Is there a version of this idiom for Objective-C implemented anywhere?

andand at rubygems

like image 919
James Avatar asked Jan 02 '12 01:01

James


1 Answers

I'm not a Ruby programmer, so I may be missing something subtle, but it appears that andand makes it so that you can safely chain method calls even when one method call may return nil. This is built in in Objective-C, because calling methods on (actually properly termed sending messages to) nil is safe and perfectly acceptable. Messages to nil always return nil, and are basically a no-op. In Objective-C this is fine:

id foo = [someObject objectByDoingSomething]; // foo might be nil

id bar = [foo objectByDoingSomethingElse];

// If foo is nil, calling objectByDoingSomethingElse is essentially
// a no-op and returns nil, so bar will be nil
NSLog(@"foo: %@ bar: %@", foo, bar);

Therefore, this is fine too, even if objectByDoingSomething might return nil:

id foo = [[someObject objectByDoingSomething] objectByDoingSomethingElse];

From The Objective-C Programming Language: "In Objective-C, it is valid to send a message to nil—it simply has no effect at runtime." That document contains more detail about the exact behavior of calling methods on nil in Objective-C.

like image 133
Andrew Madsen Avatar answered Sep 30 '22 12:09

Andrew Madsen