Functional programming and F#: Introduction

August 26th, 2008

Computer programmers sometimes mistake brevity for elegance, especially when discussing the relative merits of programming languages. Haskel partisans, for example, love to show how one can implement QuickSort in one line of inscrutable gibberish that looks like somebody had an epileptic seizure with the caps lock on. Haskell is a great language, but not because it saves you some typing. If being concise is really all that important, one might as well define a new programming language called ZipC, whose “compiler” is defined as “gunzip -c $1 | gcc”. You’ll get some really concise and “elegant” programs out of that, I’m sure! I’m usually pretty wary of academic languages like Lisp and ML, which often put computer science orthodoxy above usability. I’m just not interested in investing the time to learn a new language just so that I can save some typing and use cute tricks. The time saved is likely to be more than offset by the inefficiency of maintaining competence in multiple special purpose languages.

F#, however, is the first new language in a long time that I’ve felt is worth taking the time to learn. Developed by Microsoft research in England, F# is a functional language with roots in ML. Unlike many academic functional languages, however, F# is a pragmatic mix of imperative object oriented programming and functional constructs. Instead of forcing a paradigm on you, it simply makes several available. It can also leverage the full .NET framework, and is thus just as capable of implementing a GUI as it is an abstract recursive algorithm. It produces code that’s about as fast as C#, and it should only get faster with improvements in its CLR compiler and in .NET’s JIT compiler. A novel aspect of F# (in the context of .NET languages) is that it can be used as an interactive scripting language from within Visual Studio, allowing for interactive data visualization.

After working with it for a month or so, I find it to be a highly productive and expressive language, especially for numerical algorithms. It manages to be concise and high-level while maintaining coherence and readability. Well-written functions in F# are easier to follow and debug, relative to C++ or C#, and there are fewer opportunities for bugs to begin with. More than just cute syntax, it’s a language that actually encourages you to think differently. Programs implemented well in F# are a closer representation of the underlying concept and thinking, and are less obscured with with mundane details. Perhaps the best argument of all is empirical: the test program I wrote to compute fractal Newton basins worked the first time I compiled it, something that virtually never happens to me with C or C++.

In this post, I’ll provide a rough overview of functional programming and F#. There are much better introductions out there, but I nonetheless wanted to write this as a way to help myself learn about functional programming. I also figure F# is new enough that many of the people who read this blog might have not yet heard of it, and any small additional exposure this great language gets is worth it. This is not meant to provide a tutorial that will bring you up to speed on F#, but is intended to give you enough of an idea about it that you can decide whether or not you want to learn more.

In a follow up article, I’ll step through a short program in F# which uses some of the example functions I define below to implement a parallel computation of some pretty fractals generated by running Newton’s method for polynomial roots in the complex plane. In a third post, I’ll talk about some of the libraries available to speed up F# development. Because of the functional nature of F#, libraries written for F# can do some pretty impressive things. For example, the fractal generator detailed in the next post uses a third-party library function that handles all the details of multithreaded task parallelization through the surprisingly simple use of higher-order functions. In fact, parallelizing the program required typing exactly nine characters.

Read the rest of this entry »

Edwards did have an affair? I can’t believe it!

August 8th, 2008

Ever since I found out Al “We’re all going to die” Gore’s mansion requires its own small spotted owl-fired power plant to heat the pool, I’ve started to suspect politicians may be duplicitous as a group. So I’m not surprised to find out yet another politician turns out to be a falsely sincere hypocrite. No, the real news here is that the National Enquirer was right about something! They scooped all the major media outlets for this story. Now how did that happen?

Weird city

August 6th, 2008

This is one of the more amazing things I’ve ever seen a human do. I’m so glad that hyper-creative people like this guy exist on the planet. I’m equally glad I’m not inside this dude’s head…


walking from blu on Vimeo.

How to quit your job with an iPhone 3G

July 30th, 2008

In ten easy steps:

  1. Purchase an ’R’ rated movie from the iTunes music store.
  2. Pause movie during particularly noisy sex scene, preferably one involving farm animals.
  3. Turn off phone.
  4. Go to important meeting with your entire staff, including boss.
  5. Turn off ringer using mute switch and put phone to sleep.
  6. Think you’re safe.
  7. Innocently pull out headphones from jack, momentarily shorting out badly designed mechanism in jack used to sense the remote play switch.
  8. Remain blissfully unaware that you’ve just set a chain reaction in motion which will destroy your career.
  9. Sit in stunned horror a few seconds later as sounds of impure love eminate loudly from your shirtpocket in the middle of your boss’ presentation, despite the silent switch being on.
  10. Run back to office in tears to polish up resume.
  11. (Optional.) Write Steve Jobs an angry letter about how good design includes more than just polished metal.

(No, this didn’t happen to me. At least not exactly. It wasn’t a meeting, it was a seminar. And my boss wasn’t there, thankfully. And instead of farm animals, it was far worse: it was emo music.)

iPhone 3G initial impressions

July 28th, 2008
iPhone maps

iPhone maps

Last Friday (through means which I’m too embarrassed to publicly discuss) I got an iPhone 3G. Here are my initial impressions after using it for a couple of days.

Screen. Visually, it’s near perfect. Bright and with sufficient field of view. The only problem I have with it is that sometimes my finger just won’t slide over its surface. I don’t know if I’m just some sort of physical mutant, or if I’ve got weird finger chemistry, but sometimes it’s just unusable as a touch screen as my finger sticks to it, especially if the screen has just been cleaned. It seems that the screen was designed to work best when covered by a thin layer of grime from you fingers. I just don’t get why everybody loves this so much, but I guess I’m just weird. This problem was solved by getting a matte protective anti-glare film for the screen. The display isn’t as sharp, but its finally a pleasure to use the touch screen. I recommend you play with the iPhone in the store for a while and actually use it (try scrolling and dragging) to make sure you like dragging your finger across polished glass a million times a day.

3G network. This is a bit of a disappointment. As many many other people have found, the 3G reception is poor, and a huge battery killer. With 3G turned on I can’t get through a full day without having to recharge. Where I live in Cambridge the signal is so bad that calls will degrade and occasionally drop. It fluctuates between zero and three bars. Cambridge ain’t exactly the middle of nowhere, however, and I expect AT&T’s network is better than the iPhone’s performance would indicate. From what I’ve heard, this is a problem with the iPhone; an AT&T 3G phone from another manufacterer will often have five bars sitting right next to an iPhone with one.

I will say this, though: when it works, it’s quite fast, and I usually see speeds of around 1 Mb/s. Fortunately, you can disable 3G from the phone settings, but unfortunately there’s no way I can disable the $10 a month extra I’m paying for it. From all my previous experiences with Apple, I knew I was asking for trouble by buying the first batch of anything. Apple brutally punishes early adopters like no other company.

If there’s an excuse for this poor performance, it’s the near engineering miracle Apple had to pull off to get everything to work. In one tiny package, the iPhone contains GPS, multi-band 2.5G, multi-band 3G, WiFi, and Bluetooth radios. That’s a lot of RF going on in one place, and they all have to share antennas. I’m kind of amazed it works at all, frankly.

Data integration. For now, the iPhone only integrates natively with iCal (on a Mac), Outlook and Exchange. Fortunately, if you use Google calendar, there is a wonderful solution available from www.nuevasync.com. The folks at NuevaSync have essentially built an Exchange server that can pull your contacts and calendar from various online services (Google and Plaxo, for now) and make it available from the industry standard Exchange protocol. A brilliant idea, and a very timely one given the release of the iPhone 2.0 software which allows for Exchange integration and push. When I (or my wife) edit a calendar item online, it instantly appears on the iPhone.

App Store. As everybody predicted, there is a plethora of putative social networking revolutions, with trendy names like beepo and blue lemmingster, etc. But there are some surprisingly good apps available, and it seems the best ones are free. Some highlights: Bloomberg has an app gives you access to beautiful stock charts and a live news feed. AOL Radio provides dozens of live streaming radio channels across several genres, and it works over the cell network.

As Apple opens up the API more and more, I think the biggest impact of the iPhone will be as a new development platform for connected mobile applications. The most powerful applications of the phone are those which use the wireless broadband to connect to remote information and computing resources. It’s very satisfying, for example, to be out walking around outside and yet have access to the terabytes of satellite photos in Google Maps. On a more frivolous level, there is Shazamm, a program that will tell you the name and artist of virtually any song based on a 15 second sample played into the phone. One of the most interesting examples of the mobile-to-cloud computing paradigm is Jott, an app which will transcribe dictated notes. It records and compresses your voice at the iPhone, and then sends it to India where it is transcribed by a person and then sent back to your phone as text. I’m looking forward to seeing what other kinds of applications are enabled by having a computer in your pocket with an always-on broadband internet connection. The iPhone isn’t so much a phone in this context as it is a rich mobile interface to remote supercomputers.

What’s missing. Cut and paste, for one. Video conferencing. Live mobile TV, such as AT&T makes available on some of their other cell phones. Flash support in the browser. The ability to read PDFs anywhere but within an e-mail attachment or from a webpage. Push Gmail.

What’s just plain bad. The third from worst design flaw I’ve seen is that turning off the sound doesn’t actually turn off all sounds. Music can still play through the speaker in certain cases, and not all apps respect the mute setting. The second worst is that when you unplug the headphones, the phone sometimes turns on whatever music you were last playing in the iPod software (it fools the phone into thinking you momentarily hit the play button on the headphone remote). The absolute number one design flaw is that the second and third worst flaws can combine, so that you can end up blaring music in the middle of a lecture just by pulling out your headphones. I presume Apple will fix this in an update.

The 2.0 software feels like an early beta. The interface is often unresponsive, taking a few seconds to do something as simple as open a field for editing (the contacts program, of all things, is the worst offender). The browser crashes fairly regularly, and I’ve even hung the phone one or twice trying to watch a video podcast. It’s the first phone I’ve ever owned that crashes more than my laptop…

The battery life is rather poor. I haven’t gotten the phone to make it through the day yet, though a lot of that maybe that I leave the WiFi on. Regardless, I have no idea how Apple can claim five hours of 3G usage. Maybe that’s if you’re standing on the top of a cell tower.

Summary. Were it not for some of the aforementioned issues, it would be a truly remarkable piece of technology, especially in terms of the wonderful interface. It’s more enjoyable to use than a computer for most small tasks like checking e-mail. While I really love the iPhone in many ways, I have to admit that it’s clearly not worth the money when you factor in the plan. Of course, I’m kind of loath to return it at this point. It’s a kind of irrational psychology that is probably responsible for most of Apple’s revenue, I suspect: In the end, it’s just cool, and it would be hard to go back to klunky, even if klunky gets the jobs done for half the price. Look-and-feel counts for more than anybody (certainly I) would like to admit. Steve Jobs is a genius for being so cynical as to truly plumb the limits of this. So, I’m gonna stick with my heavy, big, overpriced, crashy, no-battery-life, embarass-me-in-meetings iPhone. Because it’s just so goddam fun to scroll around with a flick of your finger!

Fifteen things I know about God

July 23rd, 2008

Despite a long history of really tortured attempts at a so-called ontological argument for God, which usually involve some sort of lame circular logic along the lines of “something perfect wouldn’t fail to exist, so God must exist,” logic cannot be used to prove God exists, let alone understand its full nature. I like Hume’s argument that there’s no such thing as an a priori proof of the existence of anything. (And if a proof did exist, wouldn’t that render the notion of faith moot?)

Having said this, logic, restricted to proper domains, can still be used to make conclusions about what God cannot be. And that’s still fun, right? An example: God is not the San Diego Chicken. Proof: the San Diego Chicken was created by Ted Giannoulas, who was created by God. Something cannot create itself, thus God is not the San Diego Chicken. Quod est demonstratum. Along the same lines, here are a few more things I believe one can prove.

God is not:

  1. Angry.
  2. A Yankees fan.
  3. The kind of dude who would “choose” a group of people.
  4. At all disappointed that the Lakers lost.
  5. A man.
  6. A woman.
  7. Alanis Morrisette.
  8. Going to pay a lot for this muffler.
  9. Saying a word.
  10. Spelled with a ‘Z’.
  11. White.
  12. Wearing any pants.
  13. Up.
  14. Responsible for your touchdown.
  15. Particularly concerned with helping you avoid suffering.

Proofs are left as an exercise to the reader. A hint: first prove the lemma that God is not human, proceeding similarly to the proof for the non-divinity of the San Diego Chicken. All else follows fairly trivially from that, except maybe 13, which requires group theory.

Maybe “moral hazard” should be taken more literally

July 22nd, 2008

In this whole mortgage mess, the phrase “moral hazard” comes up an awful lot. When capitalism gets out of line, I think it’s always tempting for capitalists to look at incentives, say they reward bad behavior, and then focus thereafter on the incentives as the problem. But aren’t there always incentives for bad behavior? Isn’t that the whole point of cheating; because if it works it pays off?

Another common phrase these days is ”incentivization,” an Orwellian neologism that implies the only thing keeping us from turning into complete savages and pillaging our neighbors is that we are otherwised directly compensated for not doing so. It’s a conceit of academic economists, I think, who hate the idea that there are aspects of a good society that can’t be understood with an equation.

The main problem with the mortgage debacle is pretty simple, even if the finances aren’t: some bad people cheated. There are ways to fight that, but not ways to guarantee it never happens. There is no system in the world that will eliminate every reward for bad behavior. The FNM managers probably broke laws and certainly violated their fiduciary responsibility, at the very least, but we’re to believe that the real problem was the moral hazard created by their implicit government backing? Chicken shit. The modern world is rife with moral hazard: we are almost never held accountable for our actions on behalf of others, and most of us work in situations where we are on the hook for very little of what is at stake. What ultimately keeps people from taking all manner of advantage of the myriad safety nets in our world (the GSEs are just an extreme example) is something that is not at all fashionable to discuss: morality. Not the religious pious type, but the social-minded morality that compells one to act honorably even if we haven’t been direcly incentivized to do so by some board of managers. Because cheating really does work out quite well for the individual who does the cheating.

These Wall Street crooks should be detested as pariahs, not seen as the inevitable victims of a poorly designed reward system. This is not to say we need no laws, or that incentives should be ignored, just that they are neccesarily but not at all sufficient conditions to a proper functioning society. Integrity cannot be regulated into people.