What Is the most beautiful code you have ever seen or written yourself? I think John Carmack?s Unusual Inverse Square Root is pretty good

float Q_rsqrt( float number )
  long i;
  float x2, y;
  const float threehalfs = 1.5F;

  x2 = number * 0.5F;
  y  = number;
  i  = * ( long * ) &y;  // evil floating point bit level hacking
  i  = 0x5f3759df - ( i >> 1 ); // what?
  y  = * ( float * ) &i;
  y  = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
  // y  = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed

  #ifndef Q3_VM
  #ifdef __linux__
    assert( !isnan(y) ); // bk010122 - FPE?
  return y;
102 accepted

Wow, you and I have different ideas of beautiful code, I guess. IMnHO, "beautiful" code is clear, concise, and (most importantly) self-documenting. None of the examples I've seen so far in this thread are remotely understandable when you look at them -- even if you read the comments.
Not to be unpleasant, but I'll take an undocumented bubblesort over these examples any day.


Code I'm most proud of would be the main.cpp file of a Nintendo DS game I wrote, it was a Pong / Space Invaders merge.

// main.cpp
#include "header.h"

int main(int argc, char ** argv)
    while(true) // Keep app running
     while(game.lives) // New Round
      while(!game.gameover) // Neither player missed the ball

       // Sleep
    return 0;

I like it because it's clean and easy to read, it's almost psuedo-code.


Let's face it, many of us in this industry were introduced to programming by some variation of the following code:

20 GOTO 10


It's so much better than "Hello World".

#include                                     <math.h>
#include                                   <sys/time.h>
#include                                   <X11/Xlib.h>
#include                                  <X11/keysym.h>
                                          double L ,o ,P
                                         s[999],E,h= 8,I,
                                        1E3,r,t, u,v ,W,S=
                                        a,B,A=32.2,c, F,H;
                                        int N,q, C, y,p,U;
                                       Window z; char f[52]
                                    ; GC k; main(){ Display*e=
 XOpenDisplay( 0); z=RootWindow(e,0); for (XSetForeground(e,k=XCreateGC (e,z,0,0),BlackPixel(e,0))
; scanf("%lf%lf%lf",y +n,w+y, y+s)+1; y ++); XSelectInput(e,z= XCreateSimpleWindow(e,z,0,0,400,400,
0,0,WhitePixel(e,0) ),KeyPressMask); for(XMapWindow(e,z); ; T=sin(O)){ struct timeval G={ 0,dt*1e6}
; K= cos(j); N=1e4; M+= H*_; Z=D*K; F+=_*P; r=E*K; W=cos( O); m=K*W; H=K*T; O+=D*_*F/ K+d/K*E*_; B=
sin(j); a=B*T*D-E*W; XClearWindow(e,z); t=T*E+ D*B*W; j+=d*_*D-_*F*E; P=W*E*B-T*D; for (o+=(I=D*W+E
*T*B,E*d/K *B+v+B/K*F*D)*_; p<y; ){ T=p[s]+i; E=c-p[w]; D=n[p]-L; K=D*m-B*T-H*E; if(p [n]+w[ p]+p[s
]== 0|K <fabs(W=T*r-I*E +D*P) |fabs(D=t *D+Z *T-a *E)> K)N=1e4; else{ q=W/K *4E2+2e2; C= 2E2+4e2/ K
 *D; N-1E4&& XDrawLine(e ,z,k,N ,U,q,C); N=q; U=C; } ++p; } L+=_* (X*t +P*M+m*l); T=X*X+ l*l+M *M;
  XDrawString(e,z,k ,20,380,f,17); D=v/l*15; i+=(B *l-M*r -X*Z)*_; for(; XPending(e); u *=CS!=N){
                                   XEvent z; XNextEvent(e ,&z);
                                         N-LT? UP-N?& E:&
                                         J:& u: &h); --*(
                                         DN -N? N-DT ?N==
                                         RT?&u: & W:&h:&J
                                          ); } m=15*F/l;
                                          c+=(I=M/ l,l*H
                                          +I*M+a*X)*_; H
                                           )/S; K=F*M+(
                                           h* 1e4/l-(T+
                                           a=2.63 /l*d;
                                           X+=( d*l-T/S
                                            *(.19*E +a
                                            )-M* v +A*
                                            Z)*_; l +=
                                            K *_; W=d;
                                            "%5d  %3d"
                                            "%7d",p =l
                              O*57.3)%0550,(int)i); d+=T*(.45-14/l*
                             X-a*130-J* .14)*_/125e2+F*_*v; P=(T*(47
                             *I-m* 52+E*94 *D-t*.38+u*.21*E) /1e2+W*
                             179*v)/2312; select(p=0,0,0,0,&G); v-=(
                               )/107e2)*_; D=cos(o); E=sin(o); } }

From 1988, a flight simulator written in C.

Compile info here


Some could argue that the source code for TeX is pretty good.

Donald Knuth wrote some books (the art of computer programming), and was not pleased with how they were being typeset.

So he invented TeX, which is, to this day, still very widely used for documents with lots of math or mathy notation. It also happens to be a Turing-complete language.

Along the way he pioneered the idea of literate programming - that you can write a program which reads like a book, and can be separately compiled into a coding language (he chose pascal) and a human-readable document.

The feature set for TeX has been frozen for many years, and the only changes have been bug fixes. The current version is 3.1415926 (as of March 2008), and it is planned to become exactly pi after Knuth is done (aka dies). Seriously.

So, in effect, we have some extraordinarily well-tested, well-documented code, written primarily by one of the greatest computer scientists of our time.


You have a strange eye for beauty. That code may be extremely clever, but it's hardly beautiful. To me, beautiful code is code that's a completely clear and obvious solution to a tricky problem. My favorite is the Y Combinator:

(define (Y M)
  ((lambda (F)
     (M (lambda (A)
          ((F F) A))))
   (lambda (F)
     (M (lambda (A)
          ((F F) A))))))

I actually prefer the reduced version which allows the Y combinator itself to be recursive (and much more compact, though it can no longer be considered a "combinator"):

(define (Y M)
  (M (lambda (A)
       ((Y M) A))))

Many different kinds of code I find beautiful, but one of the pieces that struck me the most is (I found it on the internet somewhere at some point):

while (*a++ = *b++);

Which will copy a string in C/C++. It should never really be used in real code because it is a bit cryptic, but its simplicity is also quite elegant.


Duff's Device.


How about MapReduce, which Google uses to do much of their distributed calculations. Simple yet effective.


Actually even better



I think the most beautiful piece of computer code is McCarthy's Lisp code for a Lisp interpreter. Here it is translated into Common Lisp from Paul Graham's excellent article "On Lisp":

 (defun null. (x)
   (eq x '()))

 (defun and. (x y)
   (cond (x (cond (y 't) ('t '())))
         ('t '())))

 (defun not. (x)
   (cond (x '())
         ('t 't)))

 (defun append. (x y)
   (cond ((null. x) y)
         ('t (cons (car x) (append. (cdr x) y)))))

 (defun list. (x y)
   (cons x (cons y '())))

 (defun pair. (x y)
   (cond ((and. (null. x) (null. y)) '())
         ((and. (not. (atom x)) (not. (atom y)))
          (cons (list. (car x) (car y))
                (pair. (cdr x) (cdr y))))))

 (defun assoc. (x y)
   (cond ((eq (caar y) x) (cadar y))
         ('t (assoc. x (cdr y)))))

 (defun eval. (e a)
     ((atom e) (assoc. e a))
     ((atom (car e))
        ((eq (car e) 'quote) (cadr e))
        ((eq (car e) 'atom)  (atom   (eval. (cadr e) a)))
        ((eq (car e) 'eq)    (eq     (eval. (cadr e) a)
                                     (eval. (caddr e) a)))
        ((eq (car e) 'car)   (car    (eval. (cadr e) a)))
        ((eq (car e) 'cdr)   (cdr    (eval. (cadr e) a)))
        ((eq (car e) 'cons)  (cons   (eval. (cadr e) a)
                                     (eval. (caddr e) a)))
        ((eq (car e) 'cond)  (evcon. (cdr e) a))
        ('t (eval. (cons (assoc. (car e) a)
                         (cdr e))
     ((eq (caar e) 'label)
      (eval. (cons (caddar e) (cdr e))
             (cons (list. (cadar e) (car e)) a)))
     ((eq (caar e) 'lambda)
      (eval. (caddar e)
             (append. (pair. (cadar e) (evlis. (cdr e) a))

 (defun evcon. (c a)
   (cond ((eval. (caar c) a)
          (eval. (cadar c) a))
         ('t (evcon. (cdr c) a))))

 (defun evlis. (m a)
   (cond ((null. m) '())
         ('t (cons (eval.  (car m) a)
                   (evlis. (cdr m) a)))))

It is powerful, concise and deep. Alan Kay described it as "Maxwell's Equations of Software".

The original code can be found here along with a discussion and link to the Lisp 1.5 manual.


How about a fractal tree in LOGO?

to tree :size
    if :size > 1 [
        fd :size
        rt 45
        tree :size*0.6
        lt 90
        tree :size*0.6
        rt 45
        bk :size

Run it here, and tack this on the end to position and size it:

bk 150
tree 90

I answered in a previous post

The Jaromil bash forkbomb, once explained looks beatiful to me :)

:(){ :|:& };:

This is an explanation of the Jaromil program

Also, the more concise Windows shell forkbomb is a sure winner in any golf match:


The Haskell prelude. Specially the List module. Sample which gives me an erection:

(++) :: [a] -> [a] -> [a]
[]     ++ ys = ys
(x:xs) ++ ys = x : (xs ++ ys)

Let's see how many down votes I get for this, but I think this is some beautiful vb.net code. Wanna know why? forget the language, but the beautiful part comes in because it's freakin' simple. Someone that comes after me has to take like 10 seconds to figure out how it works and needs to be changed. Also, it's something from the real world (client dictated language choice, if you must know), not glamorous or insanely awesome, just straightforward (WORKS) and easy to read.

Protected Sub SubmitButtonClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click

            If Page.IsValid = True Then
                If IsUserCampaignMember() = False Then
                End If
            End If

        Catch exc As Exception
        End Try

    End Sub

For me it's x=42-x . 42 could be any number, it depends on what you need, but the result is that x will toggle between 2 numbers. So if x was 0 it will alternate between 42 and 0 all with one clean piece of code.

using System.Linq;

Not really, but it seems to make a lot of other things more beautiful ;)

For prettiness, I really like a lot of the sequence and pattern matching functions in F#. But for "beautiful" I pretty much agree with Danimal.


Most beautiful code?

The one which is on your mind and yet to be written ;)


My personal favorite:

bool b;
int x, y;
int q = -!!b&x|-!b&y;
 int sum = list.Sum(s => s.Value);//list is a Collection of object which has property Value

How many lines it would have been taken if there was no LINQ. I like LINQ , it reduces and simplifies the code a lot


Another beauty I got from Paul Graham:

(defun foo (n)
  (lambda (i) (incf n i)))

which takes a value and returns an accumulator function for that value. I found it a really clever, cool use of closures. Though, I prefer Ruby to Lisp, so here's a Ruby version:

def foo(n)
  lambda { |i| n += i }

... for certain values of beautiful.

for(int i = 0; i < adj.length;i++){
    for(int j = 0; j < adj.length;j++){
     for(int k = 0; k < adj.length;k++){
      adj[j][k] = Math.min(adj[j][k],adj[j][i]+adj[i][k]);

Given an adjacency matrix where adj[i][j] means the edge cost from i to j this computes the length of the shortest path between all possible nodes.


I think some of the more complex generators in Python.

They just make me feel warm and fuzzy inside.

Brian Gianforcaro


The most beautiful code I ever wrote was an N-connected components algorithm for Bell Labs in the last 80s. We had been doing signal processing with an Order(n^2) algorithm and no one thought it could be done any faster. Using a recursive function written in Lisp, I managed to create an algorithm that was a pure Order(n) that ended up being published in the Bell Labs journal and making me (very briefly and very moderately) famous.

Sigh...and then I left the job and forgot the algorithm. I thought of this because SQLMenace asked for code examples that people here have written. I wish I still had the code...


I find code beautiful that's instantly understandable:

5.times {  print "*" }
3.upto(6) {|i|  print i }
('a'..'e').each {|char| print char }

Simply beautiful. I love Ruby's loops.


Believe me or not, this draw a ASCII Mandelbrot using T-SQL. Awesome.


It's not exactly beautiful, but I'm quite happy with my webcam proof-of-concept application for Silverlight. It uses C#<->JavaScript<->ActionScript integration, and there is just so many moving parts that it feels really MacGyver when it comes together. But it works really nice and it's only about 40-50 lines to get it to work.


Read Implementing Business Partners the RESTful Way from Beautiful Code, avaiable at Google Books.

That's clean, that's readable, understandable. That's beautiful.


From Seaside 2.8, this message illustrating passing control between Web components in a seemingly statefull way accross the Web.

WAComponent >> call: aComponent
    "Pass control from the receiver to aComponent. The receiver will be
    temporarily replaced with aComponent. Code can return from here later
    on by sending #answer: to aComponent."

    ^ AnswerContinuation currentDo: [ :cc |
        self show: aComponent onAnswer: cc.
        WARenderNotification raiseSignal ]

Doing so much in so little, and almost as simple as saying it...


Factorial has a nice recursive symmetry.
Unfortunately the naive version is not much use for real life (but a good academic exercise).

// No bounds checking. Use at own risk.
int fact(int n)
    if (n == 0) return 1;
    return n * fact(n - 1);

I nominate de Moor & Gibbons "Bridging the algorithm gap: A linear-time functional program for paragraph formatting"

for several reasons:

  • everyone can understand and relate to the problem

  • the paper is the code; it's a literate script; you can save the document as text and run it thru your interpreter or compiler

  • to optimize, they apply transformations to their initial program. One can be confident that the optimizations don't introduce bugs, provided the transformations are valid.

  • Their reasoning about the problem points towards actually achieving "software engineering" - that is, they engineer a solution to the problem, rather than crafting a solution.

After some preliminaries, the paper lays out the problem (the line starting with > are code):

In the paragraph problem, the aim is to lay out a given text as a paragraph in a visually pleasing way. A text is given as a list of words, each of which is a string, that is, a sequence of characters:

>type Txt = [Word] 
>type Word = String

A paragraph is a sequence of lines, each of which is a sequence of words:

>type Paragraph = [Line] 
>type Line = [Word]

The problem can be specified as

>par0 :: Txt -> Paragraph 
>par0 = minWith cost . filter feasible . formats

or informally, to compute the minimum-cost format among all feasible formats. (The function filter p takes a list x and returns exactly those elements of x that satisfy the predicate p.) In the remainder of this section we formalise the three components formats, feasible and cost of this specication. The result will be an executable program, but one whose execution takes exponential time. The function formats takes a text and returns all possible formats as a list of paragraphs:

>formats :: Txt -> [Paragraph] 
>formats = fold1 next_word last_word 
> where last_word w = [ [[w]] ] 
>       next_word w ps = map (new w) ps ++ map (glue w) ps 
>new w ls = [w]:ls 
>glue w (l:ls) = (w:l):ls

(Here, the binary operator ++ is list concatenation.) That is, for the last word alone there is just one possible format, and for each remaining word we have the option either of putting it on a new line at the beginning of an existing paragraph, or of gluing it onto the front of the rst line of an existing paragraph.

A paragraph format is feasible if every line ts:

>feasible :: Paragraph -> Bool 
>feasible = all fits

(The predicate all p holds of a list precisely when all elements of the list satisfy the predicate p.)

In another dozen lines, they define the cost function and have a working program; they then successively refine it to be efficient.


Int2Type by Andrei Alexandrescu;

template<int v>
struct Int2Type
   enum { value = v };

It makes possible something previously thought impossible in C++ the programming language. And that's why I think it is so beautiful...


Personally I think the design of LINQ to Objects (and LINQ in general) is beautiful. The way all it all chains together and the way that query expressions in C# only affect a very small part of the spec (without even knowing about Enumerable!) are both incredibly elegant.

The actual code to implement LINQ to Objects is (or can be) quite simple - because the design is so neat. I often find that a beautiful design is easily implemented, whereas crufty code suggests a crufty design. (Sometimes that's necessary for other reasons, such as implementing a crufty interface, but other times you can improve the code by improving the design.)

repeat x = let xs = x:xs in xs

In Haskell, this creates an infinite list where all elements are identical. For instance, repeat 0 creates the list [0,0,0,...].

What I like about is how elegantly it's expressed, and how it forces you to understand Haskell's lazy nature.

Think of it (in C terms) like instead of struct link storing a next pointer, you store a pointer to a function which returns the next link. In case of xs, it happens to return a link identical to the one you're looking at (could be the same, could be a copy), which then later again returns itself (or a copy), which then... and so forth.


ha! I'm surprised nobody mentioned brainf*ck:

Output "Hello World!"


It's beautiful, in a very strange way :)


I love functional quicksort:

qsort []     = []
qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)

Anyone has anything that they wrote themselves?


I don't think beautiful code has to be easily understandable. Where would beauty of mathematics be, if it would be all easy to understand?

I found the following code beautiful or appealing for some reason, but at the same time very difficult to understand:



It's written to be very fast (no opensource fulltext comes close), and there is some sort of "alien" beauty to it - many algorithmic techniques the code uses are quite unconventional. No wonder - one of the authors was consistently winning international programming olympiad when he was in high school.

Of course, then you have other standard examples such as Linux Kernel, Git or Python interpreter, which are held to very high quality standards, and they are therefore beautiful industrial code (at least the central parts). Also some code written by Google is pretty amazing - for example their famous hash table implementation. I think they have even more gems, but unfortunately, they are not open source.


bool statement = (statement == false);


To me, beautiful code is code that expresses the domain of the problem so well that you are unaware that you're reading code written for a machine.


That code is not Carmack's, it actually has a long history:


I was impressed with how clean and elegant his code was when they first opened up thier source though.


I think it was a scheme program I wrote for solving a generic missionary and cannibals problem.

After that it was a test harness I wrote for testing a piece of authentication code at a well-known security/anti-virus company.


Although I'm too lazy to search for an example, my definition of beatiful would be "the code which can be understood by many, and misunderstood by none". Nice syntax helps, but is not critical.


For me it is when you take code that was a mess duplication on 20 pages, and turn it in something as simple as:

public partial class About : ContentView
    private void Page_Load(object sender, EventArgs e)
       Show(PageContentEnum.About, tdAboutusOverviewContent);
Fact(int n){
   return n ? 1 : n * Fact(n-1);

This one is from an in-house level editor I had developed a while ago and I think it's beautiful because even though it's easy to take this concept and make it more complicated, I think it's hard to make this code any easier.

Besides that, it made the editor so much more user friendly :-)

class History{
 void Do(const Task &task){

 void Undo(){
   MoveTopOf(Executed, Reverted);

 void Redo(){
   MoveTopOf(Reverted, Executed);

 bool CanUndo() const{
  return !Executed.empty();

 bool CanRedo() const{
  return !Reverted.empty();
 typedef std::stack<Task> Stack;

 void MoveTopOf(Stack &from, Stack &to){

 void Clear(Stack &stack){

 Stack Executed;
 Stack Reverted;

Pretty much anything in Python.

Reason 1, is that the use of whitespaces neatly indent the code. Makes it a breeze to follow through. I've grown to hate bracket because of this. In PHP, i would use brackets like so:

if( $whatever ) {
 // do stuff

And I would cringe, when I had to take over work, and it had brackets like

if( whatever )
 // do something

In Python, this problem never arises.

Reason 2, shortcuts for many common actions, such as loops; example:

a = [1, 2, 3, 4, 5]
b = [2*x for x in a]

Amongst other neat shortcuts, such as reversing chars in a string

st = 'hello world'[::-1]

All these combined, can prevent less function/method calls and less indentation, making your code beautiful.


Seen: The identity type in the Agda programming language. Represents the fact that a thing is itself. A term of type x == y is a proof that x and y are equal. A program with such a term will not compile unless x and y are the same value.

data _==_ {A: Set}(x: A): A -> Set where
==-refl : x == x.

Terse, simple, and profound. See Algebra of Programming in Agda.