Thursday, April 14, 2011


Pretty much everyone loves Randall Munroe's XKCD comic. But, wouldn't it be better if you could read it from your Factor listener? I thought so too!

We are going to build something that lets you do this:

USING: formatting http.client images.http images.viewer kernel
regexp strings ;

We need a word that loads an XKCD comic webpage, extracts out of it the URL to the comic, and then loads it into Factor as an image object (to be displayed). In this case, we build a regular expression to look for the first URL that matches where he hosts his comic images.

: load-comic ( url -- image )
    http-get nip
    R" http://imgs\.xkcd\.com/comics/[^\.]+\.(png|jpg)"
    first-match >string load-http-image ;

Using this, we can display his latest comic strip:

: latest-comic. ( -- )
    "" load-comic image. ;

Or, knowing that each comic is numbered, a specific comic from the archive:

: comic. ( n -- )
    "" sprintf load-comic image. ;

Or, like the screenshot above, a random comic from the archives:

: random-comic. ( -- )
    "" load-comic image. ;

The code for this is on my Github.

No comments: