Categories
Uncategorized

stack based languages

The May issue of Dr Dobbs had a neat article on the cat stack based language. Pity that I’m only getting around to reading it now but I’ve been busy 🙂 In many ways, stack based languages are very elegant and remind those learning to program of the processing underlying higher level languages such as Java, which is actually implemented as stack based instructions in an abstract VM.
The cat language is essentially a statically typed version of Joy which is a reasonbly well known lambda-less functional language. Joy is useful in that you can write useful applications with it having the functionality of ISO C. It’s also straightforward to understand once you free yourself of some of the conventions of imperative languages. This is helped by homomorphism or as the Joy wikipedia page suggests:

“That is, the syntactic relation of concatenation of symbols maps directly onto the semantic relation of composition of functions”

As Joy defines functional compositions without typing their parameters it has the potential for unpredictability in its results. Whereas, every function in Cat will always produce the same number and type of results, given the same number and type of arguments.
E.g. consider an implementation of the fibonacci function in cat

define fib { dup 1 <= [] [dup 1 - fib swap 2 - fib +] if }

dup just pushes a copy of the top element (duplicates) to the stack. swap interchanges the top two elements. So calculating the fibonacci number for e.g. 5 can be thought of in terms of pushing 5 to the stack, then pushing fib which operates on 5, does the necessary comparisong and sets up the expected recursive addition defining Fib(N) = Fib(N-1) + FIb(N-2) through swapping the top two of the stack. We then push the if to the stack which operates on the 3 elements which are boolean and the true/false values.
Neat, tidy and fantastically terse if you remove the unnecessary formatting. The bracketting is obviously important however as it is used to define the variables being pushed to the stack. Cat is neat by Joy is, ironically enough, more fun!

Leave a Reply

Your email address will not be published. Required fields are marked *