Robert Fisher

Just thinking out loud

On prefix notation

If you register and log in you can add comments to my pages. If viewing the main blog page, click the # underneath an entry to comment on it.

Some claim that the prefix notation is a barrier to success for Lisp.

Consider the following C code:

#include <stdio.h>

int main(int argc, char *argv[])
{
    if(argc > 1) {
        FILE *file;
        file = fopen(argv[1], "r");
        if(file) {
            while(!ferror(file) || !feof(file)) {
                char line[256];
                if(fgets(line, sizeof(line), file)) puts(line);
                else break;
            }
            if(ferror(file)) perror(0);
            fclose(file);
        } else perror(0);
    } else fputs("Need a file name\n", stderr);
    return 0;
}

It's almost entirely prefix notation. The exceptions are the greater-than (>), assignment operator (=), & the logical-or operator (||).

Array access ([]) doesn't really fit into the prefix/infix/postfix taxonomy. Neither do the declarations:

int main(int argc, char *argv[])
FILE *file;
char line[256];

(A pendant could also mention that the comma operator is also infix instead of prefix, but that's picking nits.)

So, C is really prefix notation syntax with a bit of infix syntax for a limited set of operators.


In Scheme (or Common Lisp) you can easily create a macro that allows you to use infix notation & have a situation not so different from C. Here's an macro that implements (a simple, no precedence) infix syntax that took me about 10 minutes to write.

(define-syntax infix
  (syntax-rules ()
     ((_ (x . y))
      (infix x . y))
     ((_ x op y)
      (op (infix x) (infix y)))
     ((_ op x)
      (op (infix x)))
     ((_ x)
      x)))

This allows me to say things such as:

(infix (10 / 2) * (3 + 2)))

...which evaluates to 25.

I can use it with boolean operators as well:

(if (infix (x > 5) and (x < 10))
  (display "true")
  (display "false")))

(If I use this a lot, I may need to see if I can make a read macro to make it a bit less verbose.)


Prefix notation also matches English imperatives.

  • Give me the book.
  • Add 2 and 3.
  • Multiply x and y.
  • Display "Hello, world".

 

(give me book)
(+ 2 3)
(* x y)
(display "Hello, world")

Scheme