Tuesday, December 21, 2010

Creationism and climate change denial

I’ve noticed this more and more: people lumping “climate change denial” and “evolution denial” (creationism) into the same category. The argument is that both of these are the result of the same religious conservative “anti-science” movement. In a very narrow sense, this is true; creationists generally do not seem to believe in anthropogenic global warming (AGW), for the same bogus reasons they don’t believe in evolution. But the reverse is not true: many (most I would say) AGW skeptics are not creationists. Lumping these two things together allows the environmentalists to dismiss any criticism of the established climate change narrative as the ravings of anti-scientific religious nuts. But there are some very significant scientific and economic arguments around climate change that are most definitely not in the same class as creationist arguments. Time for some de-lumping.

One major difference between climate change and evolution is how the evidence is understood and presented. It is now a familiar experience to see someone on TV telling us we need to immediately reduce emissions to avoid climatic catastrophe. In the rare event that such a person is asked to provide evidence of a human cause, the most common answer I’ve observed is along the lines of “ice caps and glaciers are melting, and the scientific consensus is that human CO₂ emissions are to blame.” Now, when was the last time you heard someone asked for evidence supporting evolution to respond with “life forms adapt to their environment and the scientific consensus is that Darwinian evolution is the cause.” This is not a small point. The fact that “consensus” is so regularly rolled out to support AGW, but is never used to support evolution shows that the levels of scientific understanding and debate are completely different.

No one talks about the “scientific consensus” for evolution because there’s no need to: evolution has a mountain of cold hard facts on its side, all confirmed by independent observation countless times. Climate research is very tough by comparison: our observational capabilities generally aren’t good enough to falsify competing theories. Instead, we have the IPCC saying that since we can’t establish the facts by direct observation, we’ll establish them by consensus. You can’t take the IPCC publications, repeat the experiments and confirm their results, because at the end of the day it’s just opinion.

My point here is not to show that the IPCC is wrong, but simply to show that the scientific process that it follows is fundamentally and necessarily different to that of evolutionary biology, or any other hard science for that matter. Questioning the consensus-derived “facts” of climate research is not the same thing as questioning the empirically verified facts of evolution.

Another difference I think is worth pointing out is how politics is so commonly mixed with climate science, in contrast to evolution science. Tell me if this scenario sounds familiar: well credentialed scientist goes on TV and says “my research shows that climate change is likely to significantly damage coral reefs…” and barely pausing for breath continues “so it’s clear we must act to cut CO₂ emissions.” This casual connection of minor scientific research to sweeping reorganization of the world’s energy production is now so common place that people don’t find it remarkable. And if you accept the climate change problem but doubt the solution you’ll likely still receive the “denier” pejorative. Evolutionary biology simply isn’t political in this way.

Skepticism regarding climate change is not comparable to the denial of the established facts of evolution. Climate research has a long, long way to go before it achieves the level of confidence we have in evolution. It is very wrong to think that all opposition to the climate change narrative is driven by Biblical literalism.

Posted via email from lockster's posterous

Thursday, December 09, 2010

WikiLeaks

Attack and Counter-Attack

I must confess, no story in recent months has captured my attention like the still-developing WikiLeaks saga. The ongoing dump of diplomatic cables combined with Julian Assange being charged with some sort of sex crime in Sweden means this is going to be in our face for a while yet.

The response to WikiLeaks has been loud, angry, hyperbolic attacks from “tough on terror” types in the U.S., and a corresponding thoughtless, reflexive defence from many “progressive” types. Amongst the noise are a few precious thoughtful critiques.

Clearly, WikiLeaks is not engaged in terrorism, and Julian Assange is not remotely comparable to the most junior jihadist. Sarah Palin’s pronouncements on the subject are pure demagoguery (by now I think we can fairly declare that an axiom with regard to any statement she makes). And Senator Lieberman needs to seriously deflate his sense of his own importance, and recognise that maintaining the government’s operational security isn’t actually in his job description.

I believe all these clumsy attacks against WikiLeaks will fail in the end, and they deserve to fail. In fact, I think they are completely counter-productive: sympathy for WikiLeaks is growing as people become concerned about the government trying to restrict speech.

The defenders of WikiLeaks are themselves hugely overreacting, however. The “attacks” against WikiLeaks and Mr Assange so far consist of: a few random nuts-with-a-mike threatening violence, some companies cutting off service, and a number of people expressing the opinion that U.S. law has been broken. Taken together, all this doesn’t come close to being a serious attempt to censor WikiLeaks. In the event that Mr Assange is charged by the DOJ, which is unlikely in my opinion, he’ll have his day in court. In the even more unlikely event that he’s actually convicted of espionage, then it should be the law you’re complaining about rather than the enforcement of it. And as Christopher Hitchens points out, those who choose to engage in civil disobedience must be prepared to face the consequences.

(The reason I say charges are unlikely is that I can’t see how the DOJ could credibly prosecute Mr Assange without also prosecuting the editor of the New York Times, which would be sure to end in disaster. But, who knows?)

At a time when publishing a cartoon depicting the Prophet Mohammed means you run the very real risk of being murdered, I can read people earnestly telling me that Amazon and Paypal cutting off WikiLeaks represents the greatest free-speech fight of our generation. Perspective is sorely lacking here.

Transparency

Overall, I’m far more concerned about the way WikiLeaks is being lauded and defended than the way it’s being attacked. I’ve seen a call for Julian Assange to be awarded the Nobel Peace Prize and another for him to be named Australian of the Year. This is madness.

The word most often used by WikiLeaks fans is transparency. More transparency is good, and WikiLeaks provides more transparency, therefore WikiLeaks is good. Mr Assange certainly understands his fan base very well, as this is the line he takes in his deceitful, self-serving piece in The Australian. Well, I need to make a few points about transparency.

First, transparency is a means, not an end in itself. The ends are, essentially, ensuring that government office holders are acting within the law and in accordance with the will of the people. Of course, this is both a good and necessary thing. In principle, I’m all in favour of leaking government secrets when there’s a clear public interest in doing so. This has served us well in the past, and will do so again in the future.

But it must be recognised that transparency may also lead to negative ends. This is why responsible journalists weigh, as best they can, the public interest against the potential downsides before publishing leaked information. This article provides a good description of the negative ends that may result from the “transparency” that WikiLeaks has forced on us.

Now we must delve into the theories and ideology of Julian Assange. He has explained these in detail, but I shall do my best to summarise them fairly here. What the defenders of WikiLeaks don’t seem to have realised is that Mr Assange actually has no interest in improving transparency, or holding governments to account. His goal is essentially to conduct information warfare against what he views as “conspiratorial authoritarian regimes”. This is why, in sharp contrast to all the talk of transparency, WikiLeaks does everything it can to conceal its own activities. It’s an organisation built for conducting information warfare.

So, the objective of indiscriminately releasing all the diplomatic cables was not to inform the public, the objective was to impede the ability of the “regimes” to conduct diplomacy in the future. This is a goal that may very well have been achieved. Julian Assange is not trying to improve the system, he’s trying to smash it. In a nutshell, he’s an anarchist using information as his weapon. And after he has smashed every institution of liberal democracy, what then? Like any good anarchist, he has nothing more to say.

The fact that so many of the leaks have been “against” the U.S. government leads to the unavoidable conclusion that Mr Assange considers that government to be a “conspiratorial authoritarian regime”. Judging by his rhetoric, I strongly suspect he views all governments that way. Now we come to the really critical point: if Julian Assange is right about this, then his actions make perfect sense and should be supported. It should be no surprise by now that I think he is completely wrong.

It is necessary to follow the implications of accepting Mr Assange’s thesis. He is claiming that our governments that are ostensibly democratic systems working for the people, are in fact authoritarian regimes that are actively conspiring against the people. Your nation’s constitution is a lie. Our traditions of liberal democracy are actually myths. Debate is pointless. Your vote, irrelevant. Breaking the machine with information warfare is the only way to truly affect change.

Now if I try to muster every last reserve of cynicism and despair at my disposal, I cannot bring myself close to believing such a thing. Am I a naive, dewy-eyed, babe in the woods?

Returning the subject of transparency, I would argue that in historical terms we’re actually doing reasonably well on the transparency front these days. Let us consider some of the government activities that the WikiLeaks cheerleaders are generally most concerned about: detention without trial, “enhanced interrogation”, handing prisoners over to foreign authorities known to practice torture, extraordinary rendition, support for the Karzai regime/racket, I could go on. Many of these issues concern me too. But we knew about these policies before the valiant Mr Assange rode onto the scene. The leaks have, at most, underscored a few things. These policies are no more likely to be changed after the leaks than they were before.

Opponents of these harsh policies need to face up to a conclusion that appears most unwelcome to them: conspiracy and lack of transparency are not what keeps the policies alive. The real reason they persist is much more prosaic: the electorate, broadly speaking, is ok with them. What’s called for is less vandalism and more old-fashioned criticism. Make your arguments and try to convince your fellow citizens. Don’t be afraid to be boring about it (I certainly have no such fear – ha!). Or forget all that and go with cynical ranting about a public stupefied by mass media and consumerism. Either way.

In conclusion, I do not want to see WikiLeaks silenced or Julian Assange in jail for espionage (I’m not going to comment on the Swedish charges, thus far they seem completely tangential). However, those of us who believe that liberal democracy has some life in it yet need to criticise the undemocratic and destructive ideology that drives WikiLeaks. This is a secretive, unelected, unaccountable group that releases whatever information it can get its hands on. It indiscriminately and purposefully harms the ability of our government office holders to do the work we elected them to do. Our oft-derided citizenry at least have the pragmatic sense to recognise that those to whom we have delegated power can better achieve our common good when some secrecy is maintained. Julian Assange should respect that democratically determined outcome, and give up this reckless test of his pet conspiracy theories.

Posted via email from lockster's posterous

Wednesday, October 27, 2010

Some more thoughts on Apple

A few more points that occurred to me, following up on my last post.

Whither the mouse?

Since its inception in 1984, the Mac user interface has obviously been designed for desktop computers with a mouse and a keyboard. When notebook computers came along and we wanted to be able to use them without carrying a mouse everywhere, or without even a flat, stable surface to put the mouse on, they had to emulate the mouse as best they could. This may now be reversing.

In the announcement of Mac OS X Lion, there was great emphasis placed on the use of multitouch gestures as a means of control. I think Lion will be the first OS designed for notebooks with multitouch trackpads, with the desktop Macs left to emulate the MacBooks as best they can. If you consider that a sizeable majority of the hardware Apple sells today is mobile and primarily operated via some form of multitouch instead of a mouse, this move seems sensible. And all new desktop Macs ship with the multitouch-capable Magic Mouse as standard now.

The Costs of Supporting Java

With regard to Java, there's been a few comments along the lines of "all the hardware Apple sells to Java developers must more than cover the cost of the handful of engineers needed to keep maintaining Java". I think this underestimates the costs involved. Supporting Java means, in addition to the engineers, that:
  • Java must be accounted for in development plans
  • Java must be accounted for in QA plans
  • Customer support needs to deal with it
  • Security vulnerabilities need to be investigated and fixed
The true cost isn't so much the money, it's that it unavoidably diverts some of the company's attention from things it would rather focus on. While continuing with Java support wouldn't be hugely onerous for Apple, eliminating distractions that aren't bringing much benefit can really help competitiveness.

Also, as the vast majority of Java work (since the switch to Intel) has been on the GUI, I'd expect the Java team knows the guts of the Mac GUI pretty well by now. Engineering talent isn't exactly a fungible resource. There's probably a development manager somewhere in Apple salivating at the thought of having the Java people on her team.

Apple and the Server Side

Folks have pointed out that Apple is a heavy user of server-side Java in their web services. I can think of many ways they can deal with that, and have no idea which option they'll take. But I think we can be sure they've got a plan and aren't leaving it to chance. And despite everyone (including me) getting very animated over "Apple dropping Java", it's worth remembering that their Java team isn't going to be shutting down tomorrow.

More generally, Apple's plans for the cloud are completely opaque to me right now. We're all assuming they have big plans for cloud services: they built that huge new data centre, and their hardware strategy seems to imply more reliance on cloud services in the future. The iPad's greatest weakness is that so much of its functionality, including just initialising it, requires USB synchronisation with a PC or Mac. MobileMe syncing is great, but it only works for a few things.

The new MacBook Air models were just announced, including one with an 11" screen, which I think is a first for Apple notebooks. When making the announcement, Steve Jobs said something like "we think this is the future of MacBooks". With their emphasis on mobile, wireless use and limited storage, these too are crying out for more cloud services.

And I think this could be Apple's greatest weakness. If I were Steve Jobs, the thing that would worry me most about Android isn't its "openness" (however you care to define it), or the temporary situation of shelf-space in U.S. phone outlets, but the fact it is backed up by the world's best cloud services. And they're only going to get better. Obstacles remain, but the movement towards doing more and more in the cloud is inexorable. Where Google has no rival, Apple's track record is not that great. The iTunes store is a huge success, obviously, but it's not really all that "cloudy", as you need a Mac with enough hard drive to hold all your content. MobileMe is expensive, and often unreliable and slow; it really only survives due to the first class client support on Mac and iOS. The iWork service is not bad, but lacks Google's killer feature of collaborative editing. Apple has its work cut out for it when it comes to the cloud.

Flash, Core Animation and Multitouch

In my last post I claimed Flash didn't support Core Animation or Multitouch. Well, @johnyanarella set me right on that. Flash does support both of these. I haven't used that many Flash apps, so now I'm wondering to what extent the multitouch support is actually used in apps.

Friday, October 22, 2010

Java and the Mac

So Apple has quietly announced that it is deprecating its support for Java on the Mac. The wording was (not uncharacteristically for situations like this) a bit vague on the details of what this means. I think two things are definite: 1) Apple will continue to support Java 6 on Snow Leopard until it reaches end of life; which I think happens when the OS after Lion is publicly released. 2) Apple will not port Java 7+ to the Mac. The main unresolved question is whether Java 6 will be supported on Lion. My guess is that it will be offered as an optional download, similar to Rosetta in Snow Leopard. Apple won't make any promises though, as they will want to have the option to drop it if it's too much effort.

As a Mac user who has been working on the Java platform for many years, this is a fairly big deal for me. I think it's an interesting event that provides a chance to examine both Java's position and Apple's plans for the Mac. People in the Mac Java community are speculating about the deeper meaning behind this move, especially when combined with Apple effectively banning Java platform applications from the new Mac App Store. So time for me to add my speculation to the noise.

Is Apple trying to force the use of their platform and tools?

No. True, Apple has made it crystal clear on numerous occasions (the Mac App store requirements are just the latest case) that they want developers targeting their OS platforms to use their development platform (Objective-C, Cocoa, Xcode). But I don't think they are deprecating Java in an attempt to force the issue. After all, Lion will come with Perl, Python and Ruby all pre-installed.

Does Apple want to kill cross-platform desktop apps?

No. I think it's true that, strategically speaking, Apple has no interest at all in cross-platform apps (outside of the browser). But along with announcing the deprecation, the latest Apple Java release also includes brand-new support for installing multiple versions of the Java platform, explicitly mentioning support for third-party versions. It's clear that Apple has no problem at all with Java running on Macs. I think they want Oracle to take it over, but I doubt they bothered to make any sort of deal with Oracle before making this move. Update: as I was drafting this, news came through that Steve Jobs has replied to a question about this, which basically confirms that he thinks Oracle should be responsible for Java on the Mac.

Then why did Apple do this?

The reason isn't that complicated: Apple no longer needs Java. If you make a list of what Steve Jobs sees as the critical objectives for Apple, it becomes immediately obvious that maintaining a Mac port of Java is not helping to advance any of them. Of course, neither does maintaining, say, Apple's port of Python. But Python takes very little effort to port and maintain. The Java port requires a team of engineers permanently dedicated to it. Also, the huge success of iOS has given Apple the confidence that their approach to working with third-party developers is working out great for everyone. The prospect of Java developers and applications abandoning the Mac is no longer remotely scary for them. Apple have decided they'd rather pay the costs of dropping Java than keep maintaining it.

But what are Apple's critical objectives?

The main theme of the "Back to the Mac" event on October 20 was the idea of moving iPad software and hardware features into the Mac, in a way that made sense for the Mac. My theory is that Apple has now oriented its entire strategy around the iPad. I think Steve Jobs probably regards the iPad has the best thing Apple has ever made. This is because the iPad provides the "purest" user experience: you hold it in your hands, rotate it, move it, directly manipulate the information you're working with via touch, and it dedicates itself to the task at hand. Of course, the iPhone has these characteristics too, but if will forever be limited by the (obviously worthwhile) trade-off of fitting in your pocket. The larger screen size of the iPad allows the touch interface to reach its full potential.

Slight diversion: in the recent financial call, Jobs said that 7" was a lousy form-factor for a tablet. You had better believe that he meant it. I will bet that Apple will never release an iPad with a different form factor. Going smaller puts to many constraints on the options for touch UI, so you end up with a bulky iPhone. Going larger would be nice, but it rapidly becomes unwieldy (the fact the iPad can be easily held and moved around is a critical part of the "experience"). The dimensions were chosen to balance the needs of video with those of e-books. Believe me, Apple chose the form-factor it did very carefully.

And yes, something else Jobs likes about the iPad is that Apple has more control over it. While many ascribe this to cynical motives, I believe Jobs honestly sees this as being good for the customer, and part of the reason for the success of iOS devices. Whether this view is correct will, in the end, be decided in the marketplace.

What is the future for the Mac?

So Apple sees the iPad as the future. But while it might be a "pure" experience, there's obviously a large number of important things that the iPad simply cannot do1. So Macs aren't going anywhere, but Jobs wants to make them more iPad-like. In the Mac event, Jobs called out what this meant: curated App Store, full screen apps, app "Launchpad", autosave/resume. What is equally interesting is what this implies they are leaving behind. During Craig Federighi's demo of Lion on the 20th, he showed the use of swipe to switch between a) full screen apps b) dashboard c) "the desktop". Perhaps I'm reading too much into this, but what today constitutes "the Mac Desktop experience" seems, in Lion, to be just another full-screen app you can switch to. A Rosetta-like box to run "the legacy stuff". I think Lion could be Apple's first step in really redesigning the Mac from first principles.

This iPad-like approach also reinforces other trends already underway. The traditional document-centric Mac app is basically dead. Most apps will be one-window, "content-centric", and abstract the filesystem completely. And they'll be made with Apple's tools. In other words, iPhoto '11 is the model. It's going to be fascinating to see how far Apple can take this. There have been people saying, literally for decades, that the fundamental desktop concept of movable, resizable, overlapping windows was the worst idea in the history of user interfaces. Will they be proven right? I have no idea. The best part is, as others have pointed out, Windows cannot easily copy what Mac OS X is doing. Greater distinction between the keyboard/pointer OS platforms will be a great thing, in my opinion.

Where does Java fit in all this?

It doesn't. Regardless of whether you think Apple's plans for the Mac are great or terrible, it's clear that heavy-weight "cross-platform platforms" like Java and Flash, which are controlled by others, could hardly be more useless to Apple. They don't interfere with Apple's plans, but they don't help them either. Java and Flash apps don't use compelling OS X technologies like Core Animation. They're completely clueless when it comes to multitouch. Apple only cares about one "cross-platform platform": the light-weight and mobile-friendly HTML5, which they can also influence.

Will Oracle Provide Java on Mac?

I'm not sure, but I think yes. The answer to this question will also answer many questions about what Oracle really has planned for Java and JavaFX. In my opinion, JavaFX has already lost the cross-platform war to HTML5 (I like JavaFX a lot, and would love Oracle to prove me wrong here). Oracle claims to be committed to developing and promoting JavaFX, so it apparently believes it can turn things around. But there's one thing I'm certain about: JavaFX cannot succeed as a credible platform without first-class support on the Mac. If Oracle is actually serious about JavaFX (which is client-side Java now) then it needs to very soon announce that it will be adding Mac as a fully supported platform, by Java 8 at the latest. Bringing Mac support online in a Java 7 update would be better. If Oracle lets Java on the Mac rot, then the death of client-side Java will be certain and final.

Where did it all go wrong for Java?

A few people have pointed out that just 10 short years ago Steve Jobs was proudly proclaiming that the Mac would be the premier platform for Java, and now after years of disinterest Apple is finally giving up on Java altogether. How times have changed. In 2000, Apple desperately needed apps on the Mac - any apps, and of course developers. Now, it's Sun/Oracle that really needs Java on the Mac, and Apple can afford to be indifferent.

Even if Oracle produces a brilliant implementation of JavaFX for the Mac, things do not look great for Java on the client. I won't make this post even longer by discussing the reasons for client Java's failure, but it's not because Apple didn't give Java a fair chance. Speaking as someone who really believed in and supported the "write once, run anywhere" ideal of Java, the fact has to be faced: the dream is well and truly finished. Where Java has failed, HTML5 has succeeded, primarily by keeping its goals modest and being ruthlessly pragmatic.

1 But I think that we haven't even scratched the surface of what the iPad is capable of. Many of its limitations are "a simple matter of software". I think iOS 4.2 is going to give a big boost to the iPad's utility, as will iOS 5 and beyond. Having said that, there'll always be some jobs that just need a mouse pointer and a keyboard.

Thursday, September 30, 2010

Scala's Missing Monad

I've been writing more and more pure functional code in both Scala and Java recently. An issue I found myself running into quite often is this: say you have a function that sometimes returns no results (e.g. looking up a key in a map). A common way to deal with that in Scala is to return an Option:

Simple enough. But then a typical use of such a function is to map it over all members of a collection:

What I find I often want to do in a situation like this is to only bother with the results if all the applications of foo returned a result. In other words, I want to turn the strings list above into an Option[List[String]], which is Some(List(foo(1).get, foo(2).get, foo(3).get)) if all those applications of foo give values, and None otherwise. I couldn't see any method in the Scala standard library that does what I want.

As a bit of a functional programming n00b, one approach I've found to be useful is to work out the Haskell type signature of the function I want, feed that into Hoogle and see what I get, if anything. In this case, the Haskell type is:

The top Hoogle result for that is the sequence function:

And look, the sequence function works on any monad, not just Maybe/Option. For example, if my foo function had been returning Either[SomeErrorType, String], then the sequence function would give the first error in the list if there was an error, or the list of results if there was no error. So this is a useful function, but as I said, I can't find it in the standard Scala library.

When I thought about how to implement sequence in Scala, I immediately ran into trouble. It is often said that "Scala has monads", and we know that the flatMap method is doing a monadic bind. But this support isn't much more than a convention for method names and type signatures, combined with nice syntax in the form of for expressions. There is no monad type declared anywhere in the standard library. Without a monad type, the sequence function would have to be re-implemented over and over: Option.sequence, Either.sequence, List.sequence, etc.

The good news is that Scala's type system can express the monad type. And the better news is that some really smart people have already done all the work for us in a library called Scalaz. So I had a look, and lo and behold there is the sequence function:

That may look nothing like the Haskell function, but that is mostly a result of how typeclasses are expressed in Scala. Trust me, this is the same function. Also, this Scalaz function is more general than the Haskell function above. It turns out that sequence works for any "traversable" thing (not just lists) containing anything that is an applicative functor (not just monads). Haskell also has the equivalent fully generalised sequence function in the Data.Traversable library.

So what did I learn from this exercise? First that the lack of explicit types for monad, functor and friends in Scala's standard library is a greater problem than I'd expected. Second, if you're writing pure functional Scala code, you should be using Scalaz. Since all Scala programmers should be writing pure functional code, it follows that all Scala programmers should be using Scalaz!

Friday, January 08, 2010

Cocoa vs Haskell

So here's the deal - if you want to write a Mac GUI app, you want to use the Cocoa framework. As a practical system for writing desktop GUI apps, the Cocoa stack simply has no equal anywhere. Part of what makes Cocoa so great is the Objective-C language, which adds a very flexible and dynamic OOP system on top of standard C.

Objective-C turned out to be a great match for creating desktop GUIs. It's obviously a general-purpose language, but for general programming it would be no where near my first choice. My first choice right now would be Haskell, even though I'm still a beginner and I pretty much suck at it. But I get why Haskell is so good (and so much fun).

So if I want to write a Mac GUI app, can I use Haskell? I've had a play with HOC which is a very neat bit of software that bridges Objective-C to Haskell. You can call Haskell from Objective-C and implement Objective-C classes in Haskell. There are some challenges trying to use HOC—it's not exactly straightforward to get it up and running and integrated into your XCode project; and it's under active, but slow, development and doesn't have a stable release. But at a more fundamental level I've come to the conclusion that, while it's very cool, HOC probably isn't worth it.

If you can get HOC working, you'll have a full-blown bridge that lets you use Cocoa APIs from Haskell. But is that actually worthwhile? The things that Haskell excels at are basically useless when using Cocoa, which is completely based around stateful objects being mutated by events and messages. While you could have all your code—including the Cocoa GUI stuff—in Haskell, the GUI code will all be imperative using the IO monad. All the effort just gets you Objective-C with nicer syntax.

So for Mac apps, I think sticking with Objective-C for the GUI code is the best choice. As a language, it sucks compared to Haskell, but it just works very well with the Cocoa APIs. But what about using Haskell to implement the Model and do other computational heavy-lifting under the hood? This turns out to be much simpler than a full Objective-C bridge. GHC of course offers a standardised foreign function interface to C out of the box, and Objective-C is a superset of C. So you can call Haskell from Objective-C code just as you would from plain C, and it works quite naturally.

But it's a bit trickier to build a complete Cocoa application that does this. There is a HaskellWiki page that describes one approach to getting a complete XCode project set up. I tried it out and it works, although things don't integrate very well. You have to compile the Haskell code using ghc outside of the XCode build process, and you have to manually track down all the libWhatever.a files that your Haskell code needs to link against. I've made a simple demonstration project for XCode 3.2 that works for me on OS 10.6: http://github.com/quelgar/HaskellCocoaDemo. This is basically the classic Currency Converter app from Apple's Cocoa tutorial, but it does the currency calculation in Haskell. Here's the rough list of steps I performed, starting from the standard XCode template for a Cocoa Application:
  • In the project build settings:

    • Set the architecture to just "i386". GHC is today only built for 32-bit Intel on Mac
    • Add "-liconv" to "Other Linker Flags". GHC libs need it.
    • Add your GHC include directory to "Header Search Paths". For GHC 6.12.1 on my system, this was "/Library/Frameworks/GHC.framework/Versions/Current/usr/lib/ghc-6.12.1/include/".
    • Add "/Library/Frameworks/GHC.framework/Versions/Current/" to the "Library Search Paths" and mark it recursive. Not sure if this is actually necessary since we end up adding all the libraries to the project manually anyway.

  • The Haskell function that will be called from C is in HaskellConvert.hs, which uses the typical FFI stuff. You compile this with GHC like so: "ghc -c HaskellConvert.hs". This outputs various files, of which the following have to be added to your XCode project:

    • HaskellConvert.o
    • HaskellConvert_stub.o

  • You now have to add all the lib*.a files from GHC that your Haskell code needs to link successfully. The wiki page I linked to above describes one way of doing this. It's not pretty, but it works. Once you know you need a particular .a file, just drag it from the finder to the project, and accept all the defaults in the add file dialog. It will be added to the link stage automatically.
  • Modify main.m to perform the Haskell runtime setup and teardown.
  • In this demo, Haskell is called from Converter.m, so this file needs #import "HaskellConvert_stub", and then just make the call to Haskell.
Probably the biggest downside of this plain C approach vs HOC is that you can't pass Objective-C objects to Haskell (well, you can, but they are not easy to use from Haskell, to say the least). So you have to convert whatever Objective-C data structures you're using in the GUI to plain C types for interfacing with your Haskell APIs. Haskell wrappers for the OS X C APIs for CoreFoundation and the Objective-C runtime might make using Objective-C objects from Haskell feasible without a full language bridge, but I'm not sure about this.

The GHC installer for Mac installs the bulk of GHC under /Library/Frameworks/GHC.framework, but I don't think it actually works as a Mac framework. I could be doing something wrong, but adding it to XCode as a framework didn't work (XCode just said it wasn't found when I tried to build, from memory). It would be great if GHC could be made a fully-functional Mac framework, as we would no longer need to manually set include and lib search paths, or explicitly add every Haskell .a file to the project. But to make this useful, I think we'd need some automated way of building any Cabal package as a framework. I'm not sure if that's feasible.

Tuesday, December 15, 2009

Some simple Scala null tricks

Scala code often needs to deal with null references, unfortunately. Such is the price of Java interoperability. One of my favourite utility methods is:

Scala 2.8 offers this using Option(ref) instead of ?(ref). However, I can't figure out why the Scala 2.8 method accepts non-reference values as well.

Another simple thing that may come in handy is an extractor for non-null values:

What's the advantage of using an extractor? Say you have a collection of references, some of which may be null, and you want to ignore the null references: