Map, Filter and Reduce in Cocoa

After working in Scheme, Python or Ruby, all of which (more or less) support function objects and the map(), filter() and reduce() functions, languages that don’t seem to be somewhat cumbersome. Cocoa manages to get these paradigms almost correctly implemented.

map()

One would think that Objective-C’s ability to pass functions around as objects in the form of selectors would make writing a map() method easy. Observe, however, the crucial differences of the NSArray equivalent to map(). (For those unfamilar with it, map(), when given an array and a method/function taking one argument, returns the result of mapping the function onto each item of the array.)

From the NSArray documentation:

makeObjectsPerformSelector:

Sends the aSelector message to each object in the array, starting with the first object and continuing through the array to the last object.

- (void)makeObjectsPerformSelector:(SEL)aSelector
Discussion

The aSelector method must not take any arguments. It shouldn’t have the side effect of modifying the receiving array.

This is different on no fewer than two levels. Firstly, even in the NSMutableArray subclass, this method is not allowed to have side effects. Frankly, I can think of few situations in which I would need to map an idempotent function onto an array; the point of map() is to be able to apply a function quickly to every element of an array and get back the changes! Secondly, an unaware or hurried programmer would think that this function was implemented so that one could write code like this:

- (void)printAnObject:(id)obj
{
NSLog([obj description]);
}

and then do this:
[anArray makeObjectsPerformSelector: @selector(printAnObject:)];

This is not the case - the above code would just make each element call printAnObject:, not call printAnObject with each element. I’m sure that to some it seems obvious, but I, for one, found this to be an insidiously tricky wart.

However, there is a (limited) workaround.

NSArray’s valueForKey: method (somewhat counter-intuitively) returns the result of invoking valueForKey on each of the array’s elements. As such, one can map KVC functions onto arrays. For example:

NSArray *arr = [NSArray arrayWithObjects: @"Get", @"CenterStage", @"0.6.2", @"because", @"it", @"rocks", nil];
[arr objectForKey: @"length"]; // returns [3, 10, 6, 7, 2, 5]

This can be used in many helpful ways; sadly, it only works on KVC-compliant properties/methods.

Anyway, moving on…

filter()

With OS X 10.4, Apple introduced the NSArray filteredArrayUsingPredicate: method, which allows one to filter an array based on criteria established by an NSPredicate. Observe:

NSArray *arr = [NSArray arrayWithObjects: @"This", @"is", @"the", @"first", @"CenterStage", @"release", @"I", @"helped", nil];
arr = [arr filteredArrayWithPredicate: [NSPredicate predicateWithFormat: @"SELF.length > 5"]]; // arr is now [@"CenterStage", "@"release", @"helped"]

Verbose, but useful.

reduce()

Frankly, Apple don’t give us any way to do this in pure Cocoa. The best way I’ve found (if you really need this, which is less often than one needs map() and filter()) is to use the F-Script framework and apply the \ operator to an array. Unfortunately, this takes a bit of overhead.

In conclusion, Cocoa and Objective-C almost bring us the joys of functional programming. We can only hope that Leopard and Obj-C 2.0 improve on these in some way.

List comprehensions, anyone?

3 comments June 18, 2007

Sandwiches.

XKCD owns.


#include <stdio.h>
#include <unistd.h>


int main (int argc, const char * argv[]) {
if(getuid() != 0) {
printf(”What? Make it yourself.\n”);
return 1;
} else {
printf(”Okay.\n”);
return 0;
}
}

4 comments June 3, 2007

Whither High School Computer Science?

Last year, when I finally decided that I wanted to pursue a career in computing and programming, I decided to take the AP Computer Science class my high school offers (skipping Computer Science I, which uses Visual Basic 6). Though I had heard bad things about Java in the past, I figured it couldn’t be all bad - after all, in order to get kids excited about CS, they wouldn’t teach in a crappy and flabby language, would they?

Well, they did.

Now, I could launch into a rant about how CS doesn’t necessarily have anything to do with programming languages, how all that’s really important is algorithms and big-O efficiency, how aspiring CS students need math more than anything else, and so on and so forth in the vein of Knuth and Dijkstra. But I don’t believe it in the slightest. Sure, CS doesn’t necessarily have anything to do with any particular programming language, as shown by the decades of computer scientists who made stunning achievements simply through logic, mathematics and perseverance; however, CS is only interesting as an academic field because there are things which computers can do and humans can’t (and vice versa). A CS student trained without a knowledge of programming languages is nothing more than a mathematics student.

But I also believe that languages shouldn’t interfere with learning through syntactic or design flaws. Java is a major sinner in these regards. We spent several weeks going over (in excruciating detail) the difference between an int and an Integer - what, exactly, does that have to do with CS? Sure, we learned something about OOP - except for all the interesting things, such as the history of OOP, the reasons behind encapsulation, the uses of multiple inheritance (and the problems and solutions therein), and how OOP has changed from its pure Smalltalk roots to its bastardized Java form. We learned that we need to predeclare variables in a statically-typed language, but not any of the reasons why static typing may or may not be a good thing (speed, type safety, robustness, etc.).

And there’s so much we didn’t learn. We spent maybe a week on sorting and searching; never mind that the truly remarkable thing about computer-based algorithms is that they can search, sort, and process data in ways that no dead, ink-based y=mx+b equation ever could. We didn’t look at Nextstep’s use of object-orientation to power an entire operating system, quite possibly the most concrete use of OOP ever. If we wanted to focus on practical uses of Java, why didn’t we learn how to use Eclipse, the best Java IDE out there? Why did we use Java 1.4 instead of Java 1.5 or 1.6, thereby abandoning templates, primitive autoboxing and helpful classes such as Scanner?

If we truly wanted to learn about writing good code and learning the fundamentals of computer programming, we should have used Smalltalk. Using Squeak or VisualWorks or Cincom, we could learned how a truly, 100% object-oriented programming language works, the history of the GUI, how to create an intuitive GUI without endless Swing components, how to program in a robust, intuitive and simple language free of warts, and, most importantly, how to use computers to do things and solve problems that only computers can do.

Instead, we learn Java.

19 comments May 11, 2007

Cocoa Snippet: Detonate your Cursor

- (IBAction)poofCursor:(id)sender
{
NSShowAnimationEffect(NSAnimationEffectPoof, [NSEvent mouseLocation], NSZeroSize, NULL, NULL, NULL);
[NSCursor hide];
}

In case you can’t figure it out, this code shows the *poof* animation one gets when dragging items off the Dock at the current mouse location, then hides the mouse. The overall effect resembles the mouse cursor exploding.

Add comment April 18, 2007

Five Things that Suck About Objective-C and Cocoa

Things have been quiet here in this blog. Too quiet. As such, I’m keeping the name-five-things-you-hate-about-a-language-you-like ball rolling, having seen it rolled with zest and vigor by brian d foy, Titus, Jacob Kaplan-Moss and Vincent.

Without further ado:

Five Things that Suck About Objective-C/Cocoa:

  1. Syntax for NSString literals. For the uninitiated, in Objective-C code enclosing "insomnia" in simple double-quotes creates a C-style char[] string; if you wish to use the far more powerful and versatile Objective-C NSString class, you must add an @ (making @"insomnia"). Backwards-compatibility with C is a good and useful thing, but why require more keystrokes to do the most commonly-used thing? I myself last weekend puzzled over a wonderfully non-specific “invalid reciever” error for a long time before realizing that I forgot an @ when sending strings to an arrayWithObjects: method. Aside from that, why use the @-sign as a prefix for NSStrings when it’s used in a plethora of other places, such as @interface, @implementation, @end and @selector? Though 90% of my @-key-presses in Textmate are prefixes to NSStrings, I can’t have a keypress of @ automatically expand to @”" - there are too many other things to do with the poor little @-sign. The oft-neglected | (pipe or vertical bar, I’ve heard both) character is far less disruptive to the flow of typing.
  2. reallyLongAndCamelCasedMethodNamesGetAnnoying. I refer specifically to the lovely NSWorkspace method openURLs: withAppBundleIdentifier: options: additionalEventParamDescriptor: launchIdentifiers:
    And ObjC method names can be concise yet informative - take for example NSString’s compare: options: range: locale:. I must admit, this complaint is not entirely valid, especially considering Textmate/XCode’s fancy code completion.
  3. No operator overloading. Come on, guys - why reject this crucial part of Smalltalk heritage? I, for one, am sick of writing objectAtIndex and objectForKey: as compared to Python’s []. Though Smalltalk allows one to define new operators, I’d be perfectly happy to settle for a few overloadable operators (string concatenation is desperately needed).
  4. Mysterious helper methods. I didn’t know of the existence of NSHomeDirectory(), NSTemporaryDirectory(), or NSClassFromString() until very recently. True, this is my fault, but I think that F-Script’s idea of storing all of these methods in a singleton System object is excellent, and much more in line with Objective-C’s Smalltalk heritage. (Actually, I have a half-finished ObjC class that makes NSBeep() and all those other miscellaneous C functions into class methods; if there’s any interest, I’ll finish and release it. I suppose that makes this complaint invalid. Oh well.)
  5. File management is a mess. Essential code is scattered throughout NSWorkspace (in all its brain-dead glory), NSFileManager, NSFileHandle, NSPipe, NSDirectoryEnumerator, and NSData - few things are as infuriating as hunting down the correct class that does exactly what I want. (Actually, no. Finding a better solution after thirty minutes of hacking around some perceived inadequacy is worse.

So there you have it. To be honest, it took me quite a while to write this, mainly because Objective-C is such a great language and Cocoa is such a great set of libraries. I suppose that the imperfections in a consistently useful and friendly toolkits stand out, and in retrospect I sort of feel guilty for my picky attitude. After all, it could be much, much worse.

2 comments April 5, 2007

This Is Worrying


Last login: Sun Mar 18 22:39:27 on ttyp1
Welcome to Darwin!
ok-computer:~ p_trick$ python
Python 2.5 (r25:51918, Sep 19 2006, 08:49:13)
[GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
Type “help”, “copyright”, “credits” or “license” for more information.
>>> True, False
(True, False)
>>> __builtins__.True, __builtins__.False  = __builtins__.False, __builtins__.True
>>> True, False # oh dear
(False, True)
>>> if False: print “Oops.”

Oops.

Is there a reason for this?

2 comments March 19, 2007

Old School

In a raucous debate with my dad about my post regarding the merits of C, he made the following analogy:

“Condemning C because of its poor string support is like condemning a Ford Focus because of its poor ability to cruise at 35,000 feet.”

Touché, Dad. Touché.

Add comment March 18, 2007

C == Assembly

Last month John Gruber asked the question “Is C the new assembly?”

It’s a tough question - what, exactly, does ‘the new assembly’ mean? The first things that pop into my head when I think of assembly language are these:

  1. Fast (or believed to be so)
  2. Ugly and difficult
  3. Nonportable
  4. Foundation for other languages

C has all of these attributes. (And more!) But does it have these attributes in such a way that it can be called ‘the new assembly’? I think so.
(more…)

13 comments March 4, 2007

Do You Believe in (Coding) Magic?

This article reflects merely my own thoughts and opinions. I doubt it applies to you personally, so don’t think I’m proposing a new law.

Last night, as my LAN-party-attending friends and I drove home from the pizza place, I was asked to explain the concept of Turing-completeness. I managed to give a somewhat coherent overview of the topic without simultaneously befuddling my listeners, and gave examples of Turing-complete and non-complete languages. Listing off my favorite programming languages, all of which fell in the former category, I was struck by a realization, and drifted off into thought until awoken by the derision of my peers. :)

I appreciated the furor on reddit regarding my How to Beat Rails and Blocks != Functional Programming posts; debates between programmers are often informative and always entertaining. The contests between languages, though they rarely (if ever) change anyone’s mind, are fertile ground for inflammatory quotes and flame wars. But the realization I came to in the car yesterday was this - since almost all programming languages are Turing-complete, what’s the difference? At a fundamental level, they’re all the same, right?

Then why do I like Python and Ruby so much more than C or Java? Why, indeed, doesn’t everyone just write bare machine code? Am I wasting my time wondering about abstracts instead of actually coding? I pondered these questions through many hours of video games, and eventually came to a conclusion.

The largest factor in whether I like a language is its attitude towards “magical” behavior. “Magical” behavior is difficult to define - my best effort is ‘the ability to redefine the most fundamental aspects of the language’ - but here’s an example, taken straight from the perlvar man page:

$[
The index of the first element in an array, and of the first character in a substring. Default is 0, but you could theoretically set it to 1 to make Perl behave more like awk (or Fortran) when subscripting and when evaluating the index() and substr() functions.

Perl, which I loathe with every fiber of my being, condones - nay, encourages - the deep, evil, horrible black magic to find the quickest way around a problem. Ruby, which I like more and more with every passing day, allows for happy, Good-Witch-of-the-North-esque magic with metaprogramming, different eval() scopes and near-total introspection. Python, which I’ve loved since the seventh grade, really discourages the use of magic - custom infix operators are the extent to which Pythonistas have dabbled therein. However, it always tries to permit the clearest, most concise non-magical solution to a problem. Scheme, which I respect, isn’t so much a language as a wellspring of magic through which you can do whatever you want. In the right hands, it’s brilliant, and in the wrong ones impotent. Rails and Pylons reflect the different attitudes towards magic - Pylons requires you to render the templates explicitly, while Rails just evaluates instance variables and goes with the flow.

In summary, my preferred language depends on attitude towards magic - my favorite languages either allow for positive, as-readable-as-possible magic (Ruby) or disallow it altogether (Python.) Which is better? It depends on your situation - and on the necessity of good documentation. (Documentation, and therefore long-term maintainability, cannot coexist with magic.) Overall, though, I enjoy a little code magic - do you?

13 comments February 25, 2007

*EVERYTHING* is an object in Python

A recent (and very well-written) Ruby tutorial made the oft-repeated assertion that not everything in Python is an object. This is flatly untrue, as a brief look through the console will show you:

>>> someNumber = 1

>>> isinstance(someNumber, object)

That evaluates to True.

I think that settles the matter.

5 comments February 22, 2007

Next Posts Previous Posts


About Me



I'm a college freshman, passionate about technology, programming (especially Cocoa and Python), and Apple.

By the way, 'important shock' is an anagram for 'Patrick Thomson'.

Meta

Links

Categories

Top Posts

Blog Stats