Sunday, 1 February 2009

Highlighting Code for the Web using Emacs


(defn process-pixel [x y]
((fn [x y xc yc accum]
(let [x1 (+ (- (* x x) (* y y)) xc)
y1 (+ (* 2 x y) yc)
sq (+ (* x1 x1) (* y1 y1))]
(cond

(> accum *max-iteration*) *max-iteration*
(> sq 2.0) accum
:else (recur x1 y1 xc yc (inc accum))))) x y x y 0))



On Ubuntu you can install a bunch of Emacs goodies by installing the emacs-goodies-el package.

Once you've done this, you'll have Htmlize and can just do M-x htmlize-buffer to get an HTML rendition of the current buffer. This uses CSS, so all you really need to do is whack the definitions in your Blogger template and then paste the body of the code in. Obviously you'll need something like Slime or some other Emacs package that does the highlighting.

Mandlebrot Fractals

The Mandlebrot Set is probably the most famous set of fractals. The maths behind it is dead simple and with just a few lines of code you can get some impressive results.

For any given pixel, you can work out a colour value thus:

(def *max-iteration* 512)

(defn process-pixel [x y]
((fn [x y xc yc accum]
(let [x1 (+ (- (* x x) (* y y)) xc)
y1 (+ (* 2 x y) yc)
sq (+ (* x1 x1) (* y1 y1))]
(cond
(> accum *max-iteration*) *max-iteration*
(> sq 2.0) accum
:else (recur x1 y1 xc yc (inc accum))))) x y x y 0))


The harder part is translating a number between 0 and *max-iteration* into a decent range of colours. I'll ignore this for now and stick with green!

Mandlebrot set visualization in Clojure

Source code for version 0.1 is here. Next on the list:

  • Make it look like the Math - write complex number library
  • Make it run fast - optimize (uses more cores, minimize type coercions)
  • Make it look nice - find a better colour mapping function

Refactoring is the Java term for doing work.

I think this is a great quote (and has a touch of truth about it).