Showing posts with label S-expression. Show all posts
Showing posts with label S-expression. Show all posts

20 March 2008

Prefix notation considered harmful?

I found an article on making readable S-expressions. The premise is that, as Paul Graham is quoted as saying in the article:

I've used Lisp my whole programming life and I still don't find prefix math expressions natural

I understand that prefix notation isn't what everyone learned in school, so it seems weird at first, but I find prefix and postfix notation both more logical than infix; come to think of it, I'm actually not sure why we even use infix in the classroom instead of prefix. It's an ambiguous grammar, so (ironically, considering all the whining about parenthesis in S-expressions) you need parentheses to clear up what the meaning is, or some sort of accepted precidence rules.

Postfix makes sense if you think of things like a stack, which granted most people probably don't. It's easy to understand in that sense though. If you see an operator like +, you're going to add the last two numbers you had, so 2 3 + means add 2 and 3, and you end up with 5 on the stack. Want to do (2 + 3) * 5? To hell with parentheses: 2 3 + 5 *. This is easiest for computers, but I agree it doesn't make much sense to think about math this way.

Prefix makes total sense to me, however. In prefix notation the first thing you get is what you're going to be doing. You shouldn't have to wait for the middle of an expression like 2 + 3 to find out you're doing addition; when you have + 2 3 you know from the beginning you're adding two numbers, all you need to do is get the actual numbers now. Prefix notation tends to be much more logical to read: + 2 3 is obviously "add 2 and 3". Infix notation requires a passive voice like "2 added to 3", which seems silly. Programmers take it for granted that you would call add(2,3) to use the add function to add two numbers, but balk when they see (+ 2 3) as being obviously wrong -- all Lisp has done is normalize everything instead of having an annoying mix of prefix and infix functionality.

When I first learned Lisp (technically, Scheme) I thought it was the greatest thing ever, and I loved writing things in it. I think a lot of programmers have the same experience, and yet there seems to be a growing movement to destroy the S-expression, which seems to defeat the whole point.