Playing with Nifty Assignments

I’ve been looking at Nifty Assignments. I thought it would be fun to look at the first assignment and see what it’d look like in Racket.

#lang racket
 
;; The Iron Image Puzzle
;; Part of the Nifty Assignments page by Nick Parlante.
;; http://nifty.stanford.edu/2011/parlante-image-puzzle/
 
;; We’ll use the 2htdp/image library for this one.
(require 2htdp/image)
 
;; First, grab the image by its url.
(define distorted-image
  (bitmap/url “http://nifty.stanford.edu/2011/parlante-image-puzzle/iron-puzzle.png”))
 
;; We will want to decompose the image into its individual pixels.  We can use
;; image->color-list to do this.
;; To make experimenting with the pixels an easy thing to do, let’s write
;; a function that will let us “map” across the pixels of an image
;; to get another image.
(define (image-transform an-image a-pixel-transform)
  (define colors (image->color-list an-image))
  (define new-colors (map a-pixel-transform colors))
  (color-list->bitmap new-colors
                      (image-width an-image)
                      (image-height an-image)))
 
 
;; With image-transform in hand, we can apply a filter,
;; such as zeroing out the blue and green components like this:
(define (zero-blue-green a-color)
  (color (color-red a-color)
         0
         0))
(define dark-image
  (image-transform distorted-image zero-blue-green))
 
 
;; The image is still a bit darkened.  Let’s bump up the red component
;; by a factor of ten.
(define (red*10 a-color)
  (color (* (color-red a-color) 10)
         (color-green a-color)
         (color-blue a-color)))
(define red-eye-image
  (image-transform dark-image red*10))
 
;; And now we should be able to look at red-eye-image and recognize
;; the landmark.

Notes from the Jane Street talk

Notes about the tech talk given by Jane Street (http://www.cs.brown.edu/events/talks/janestreet.2.html)

Basic idea: make asynchronous, event driven programming easier to write. Multi-stage computations, in a traditional event-driven style, requires the programmer to explicitly represent the stages as part of the program state. This can lead to an “inversion-of-control” issue in traditional event-driven programs. If I have a program that looks like:

  • do some work
  • call to the network
  • wait till the network call resolves
  • do some other work

then a traditional event driven model requires the “do some other work” entry point to have some kind of representation in the program. Something naturally expressed as a single sequence becomes a bunch of shorter, chunked functions, and the toplevel event loop needs to dispatch to them.

Jane Street’s approach is to use their Async library to handle this gruntwork. Their approach, in retrospect, is very similar to that of PLT Web server’s send/suspend: it provides a mechanism for linguistically representing the blocking chunks of computation, and let the event loop handle the instruction threading from one stage to the next.

In Jane Street’s case with their async library, they use a Deferred type, and write code in monadic style. Monads are their mechanism for representing what happens next, after a blocking call returns. The event loop handles the appropriate state-threading from one phase to the next.

The essence of the approach is that the programmer is writing in continuation-passing-style. The server manages these continuations and invokes them when each blocking call resumes. One of the things that the Async library does is to make the syntax for writing in CPS easy to express. And the CPS parts are only around blocking parts, so rest of the code doesn’t have to look unnatural.

This style seems to easily account for sequential, blocking computations. It doesn’t directly account for situations where you need branches of computations. e.g. I do ten requests to the network, but when five come back, I want to continue the computation. It doesn’t appear to be easy to naturally express this without some additional primitives, and what the Async library provides (choose, or choice?) sounds like it doesn’t handle this case with particular ease.

book report: Eloquent JavaScript

I picked up Marijn Haverbeke’s Eloquent JavaScript upon a friend’s recommendation and started reading it.

Here are some good points about the book: it takes on JavaScript from the perspective of a general purpose language, and not primarily about the web. The strongest part of the book are the many extended examples throughout the text. One of the first extended examples is a text-processing application. Another is a fairly sophisticated discrete simulation of a terrarium, the sort of thing reminiscent of a World-style program. Another includes a Sokoban implementation that uses DIV elements to present the game board. A person reading this book will come out pretty convinced that JavaScript can be used for Real Things.

Unfortunately, my reading picks up a few criticisms for the presentation and material. The book makes the motions of being an introductory text, with its first chapter talking about assembly, and how programming languages make our lives easier… but it doesn’t follow up. One of the major problems is that the book follows a grab-bag approach. Many books mistake “place an chapter at the beginning that enumerates all of the language features we’ll be using for the rest of the text” as beginner-friendly. This book commits that mistake: many chapters are a collection of language feature upon language feature.

Because of that grab-bag nature, some subjects are discussed with no satisfying depth. There are about two paragraphs of text about unit tests frameworks, and then no further mention of them. There are a few paragraphs talking about XMLHttpRequest, but no discussion about the significant implication of writing programs in asynchronous style, which really can be confusing for the beginner. The text treats these subjects as afterthoughts.

The subtitle of Eloquent JavaScript is: “A modern introduction to programming”. But it’s not really a good introductory text, nor is it a reference. The target audience that the author is writing towards is the programmer who has previous experience with some other language like Java or Perl…. but in my opinion, the best audience for this text is the JavaScript programmer! If one came into the book with a rudimentary knowledge of JavaScript, this book is great because it shows how to use JavaScript in anger. You can tell the author actually uses JavaScript as a working language, and that enthusiasm comes through in the text.

The programming style in the book unfortunately rolls right into some potholes in JavaScript. The use of “==” is persistent throughout the book. In the discussion of function closures, the text uses toplevel function declaration, as opposed to function expressions. This is a no-no! (See: http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/ for the details of why you’d want to avoid function declarations within the innards of a function.)

The use of “for (var …)” is also unfortunate, and there are bugs in the text involving it. Page 120, for example, does the following:

for (var i = 0; i < 10; i++) {
    for (var i = 0; i < 20; i++) {
        ...
    }
}

which doesn't attract the eye of someone coming from a sane language, but does strike immediate alarms to one sensitive to the weirdness in JavaScript.

This book is the kind of thing I love to read: a from-the-battlegrounds discussion on how to use a programming language in anger. It's not one of the phone-book sized tomes meant to take up bookshelf space: it's alive, with a good heart, but with some misssteps. What makes me pause is this: I know that I can make (and have made!) the same kind of mistakes that Marijn makes with regards to writing an introductory text. I hope future revisions fix the issues.

A release of Racket

Racket 5.1.2 came out recently, and I’ve been pretty happy using it so far. It feels significantly snappier than 5.1.1. It also looks like some of the graphical quirks I saw in DrRacket running under xmonad are fixed.

Documentation still needs some work, according to folks on Reddit. Although Racket has a lot of good reference documentation and quite a few tutorials, the meaty libraries like the FFI are missing the kind of treatment that the Guide provides for the basic language.

Lots of work to do!

RacketCon

I’m still recovering from the week of Program By Design, followed immediately with RacketCon. My feet are meant for walking, not standing.

The weekend was fun, though. I got to show that Whalesong, my Racket to JavaScript compiler, is starting to do interesting things. Although I didn’t tell anyone explicitly, I was dogfooding Whalesong: my entire slideshow was itself a World program that I had compiled with Whalesong itself.

Unfortunately, I was so nervous during the beginning of the talk, that I rushed my example about a slideshow being itself a world program into incoherence. I’ll have to watch myself when the videos come out, grimace, and hope to do better next time. I think folks got a kick out of the JQuery example.

Other items to note:

  • The second day unfortunately suffered from a lack of air conditioning.
  • Jay McCarthy showed a kick-butt example of game programs written with World. My ears are still ringing with the thump of the video game music.
  • Marco Morazan showed how to teach A* to first-year undergrads. Awesome.
  • Matthew Flatt talked about the history and future of Racket. He brought his magic 8-ball with him.

Ok, better get back to work and get Whalesong ready…

Buying internet service

So I went to buy a new internet cable modem from the local service provider here. The store had an air of sterility to it, the kind of soulless air that fills electronics stores like Best Buy and Fry’s Electronics.

Within the first minute or so, the salesperson was already trying to sell me a wireless router.

“No, I don’t need one; I’ve got one already,” I said.

We continued the transaction; he handed over the modem. I asked, “So I can plug this into my roommate’s router and everything will work, right?”

“Do you have the original installation disks?” he asked.

“Errr, no?” Why was he asking about that?

“Oh! Then you need to buy our wireless router!” he quickly interjected.

Holy wow. The salesperson was pushing the router hard. I got out of there as quickly as I could.

F*dging up a Racket

(A small history behind the guide at http://hashcollision.org/brainfudge)

I was listening to Randal Schwartz give an interview to Matthew Flatt on FLOSS Weekly a few weeks ago. It was really cool to listen to Matthew, who consistently gave so much credit to the PLT team during the interview. At one point, the conversation turned toward the idea that Racket could support multiple languages. Randal asked, with excitement, whether that meant Racket could potentially do Perl 6. I was hoping that Matthew would respond with a “Dear God No!” kind of horror, but he took it in calm stride, of course, and said that people were welcome to try it if they had time.

That stuck with me. I wanted to do my part in helping to make such dreams/nightmares into reality. I definitely didn’t have the time to do it myself, not without getting severely schooled by my advisors. But I still wanted to help. Maybe I could write a guide to help other hackers get started. Hopefully, I’d get in less trouble that way.

So I wanted to write an extended example of how to add a new language to Racket. It needed to cover the entire gauntlet, from setting up the PLaneT development links, to writing the semantics and parser, to finally delivering a self-contained package on PLaneT. And I needed to use a non-parenthetical language.

Sometimes it’s hard to get across the idea that Racket supports multiple programming languages. The traditional examples that people see, such as programs written in Beginner Student Language:

#lang htdp/bsl ; Any key inflates the balloon
(require 2htdp/image) (require 2htdp/universe)
(define (balloon b) (circle b "solid" "red"))
(define (blow-up b k) (+ b 5))
(define (deflate b) (max (- b 1) 1))
  (big-bang 50 (on-key blow-up) (on-tick deflate)
               (to-draw balloon 200 200))


just aren’t convincing to people, precisely because it looks just like Scheme, with all those silly parentheses, defines, and all.

But something like this:

#lang planet dyoo/bf
++++++[>++++++++++++<-]>.
>++++++++++[>++++++++++<-]>+.
+++++++..+++.>++++[>+++++++++++<-]>.
<+++[>----<-]>.<<<<<+++[>+++++<-]>.
>>.+++.------.--------.>>+.


… now there’s something deliciously perverse and screwed up about this! The choice was clear: the language had to be brainf*ck.

I spent an afternoon getting the code ready. For days, though, my brain was full of the document. Writing is hard! I wanted to keep the number of concepts down as much as possible. There were two dangers I tried to avoid:

  1. Losing velocity. A person needed to be able to read it in one sitting, or else they might give up too easily.
  2. Narrowing the target audience. I want to make it accessible to professional programmers with some familiarity with a programming language like Scheme. But they shouldn’t be Racket experts.

After some struggle, I finished the first nine chapters of the tutorial. I posted it up, and tried getting it on /r/programming. Although I failed miserably at getting upvotes, thankfully, more Reddit-savvy folks posted a compelling headline, and people started looking at the tutorial. Hurrah! Mission accomplished!

… except that some people were getting caught up by the fact that the implementation was slow. Drats. I went back and saw that I had messed up a small part of the implementation. I fixed it, but then saw that I had no choice: I had to extend the tutorial to show what I needed to do to fix the performance issues. A small matter of writing again, right?

There are moments in one’s life where certain actions seem preordained and inevitable. I had just gone and re-watched an anime, episode 10 to be precise, which involved a time loop and all sorts of pain, sadness, and suffering. The optimization section, Section 10, felt very much like the same thing: I needed to go back, fix things, and keep fixing things until the implementation performed reasonably well.

That section ended up being slightly longer than the first half of the document, and as long to write. The upside was that the tutorial felt much more complete after the writing was done. The downside was I didn’t get anything else done during the week. A conservation of hope and despair, I suppose.

shimmer

One of my favorite companies is trying to kill my active area of research and personal interest. When Apple engages to hurt children, when they enforce a discriminatory and irrational policy, then they’ve crossed a terrible line. I’ve listened to the counterarguments, but I can only conclude that what they’re doing here is morally wrong.

The iPhone has lost its shimmer for me. Time for a new phone.