Postfix vs Prefix

parsingpostfixprefix

I have read at a few places, that Postfix is easier to evaluate & easier to convert to Code than Prefix.

I understand that if you parse a prefix expression from left to right, you might not be able to evaluate directly(as some operands might be prefix expressions as well); but if you parse the prefix expression from Right to left , it becomes as simple as parsing a postfix expression from left to right.

Is there still a difference that i am missing?

Best Answer

The difference is in the default execution models of prefix and postfix languages. A prefix language like say a Lisp is typically based on an lambda calculus inspired node-substitution based evaluation. So in order to evaluate

+ 1 * 3 2

I would first make a tree

+
1 *
   3 2

And then substitute inner expressions to simplify

+
1 6

7

In order to get this evaluation model I must parse into a tree. Postfix languages by contrast tend to be based on stack operators. When I write

1 3 2 * +

I am not writing 2 operations (plus and times) but 5, because each numeral represents "push the corresponding number onto the stack". Because they will be executed as a series of operators on a stack I can parse then as just a flat list of symbols rather than a tree, which is a bit easier.

Now it is definitely true that you could impose a stack semantics on a prefix notation and so treat prefix as "postfix written backwards" and conversely you could impose a substitution semantics on a postfix notation and so treat postfix as "prefix written backwards". So there is no essential difference in how difficult it is to parse prefix and postfix in themselves. Rather different execution models require different ASTs, some of which are harder to parse for than others, and these execution models are usually written in either prefix or postfix depending.

In response to question

The reason for preference is that a tree based AST with a substitutional semantics makes including variable, function, class, whatever declarations very natural (the lambda calculus was after all the first of these). Whereas there's no nice way I can see of putting these things in a purely stack based semantics (indeed all postfix languages I am aware of will have non-postfix notation and thus a "tree with flat lists for branches" AST in order to include things like function declarations or anonymous functions/control structures).

You could have a postfix language without such structures and be complete (just use SKI calculus) but they're mighty handy.

Related Topic