Why programming languages require well-specified return types from functions

Created on 2022-03-07T16:42:03-06:00

Return to the Index

This card can also be read via Gemini.

Start with a basic stack machine with a number, string and position stack. Now look at code such as this:

“Hello,”
“player name” xcall
concat
“!” concat
“say” xcall

The problem is that there is no way to know, looking only at this code, that the player name xcall consumes no input and outputs a single string. We also do not know that the say xcall will consume one string and produce nothing.

As a human you know whatever tricky nonsense you are doing with these xcalls. The computer is stupid and doesn’t know. So you have to set some kind of standard the computer does understand and store them somewhere it can find them. These are called calling conventions.

For example if we can tell the computer a function will consume two strings and output one integer then we can:

When you have a “local variable” you have to store it somewhere. When we store them on a stack we have to figure out, when you try to use it, where on the stack that value is now. For manual code (the above example) the human keeps track of it. In a modern programming language the computer has to do it (and remember the computer is not clever.)

One technique for stack machines is called “stack simulation.” This means the computer pretends to run the program (but really it isn’t running it.) During this pretending it keeps track of where values are added and removed so it knows exactly where something is when you ask for it, and can generate code to go grab that directly.

When the computer can see that you are calling a particular function that will consume X inputs and give Y outputs, it can account for that (without needing to know anything about what the function does internally) and keep track of where everything is.