Scheme from Scratch - Bootstrap v0.11 - Primitive Procedures Part 1
It is about time we applied a procedure to some arguments. The best place to start is with primitive procedures. There are many primitive procedures in Scheme:
cons, etc. To start we can add just one primitive procedure. I’ve chosen addition,
+, but you could choose another one if you like. Adding more than one primitive procedure to start would just cloud what is conceptually important about this incremental step. Tomorrow’s, part 2 of primitive procedures will be to add many more primitive procedures.
A sample REPL session:
$ ./scheme Welcome to Bootstrap Scheme. Use ctrl-c to exit. > (+ 1 2 3) 6 > (+ 3 -1) 2 > + #<procedure>
The first examples shows that addition is a variadic procedure (i.e. can take a varying number of arguments.) This is one of the benefits of using a procedure for addition rather than a binary operator as done in many languages.
The last example shows that the output for a procedure,
#<procedure>, is a bit cryptic. A primitive procedure doesn’t have any particular useful external representation and so there isn’t really anything better to print.
In the implementation, we do need to add a new internal data type
PRIMITIVE_PROC. This data type uses pointers to functions so if that part of C is a bit rusty for you then please have a look in section 5.11 Pointers to Functions of K&R 2e.
All primitive procedures will have a first line like the following with only the “
add” part of the name changed. The “
_proc” suffix of the name will be in all primitive procedure names.
object *add_proc(object *arguments)
Bootstrap Scheme is designed to run a compiler program once. A compiler program will need many more primitives than just addition. Feel free to start adding more primitives that you think will be useful in a compiler program. I’ll be adding many more tomorrow.
It’s been motivating to see Chris, Jim, Nick, Stu posting their code and seeing that their commits keep on coming. They have variations with tokenizers, flex/bison, Ada. It looks like another Chris might be starting an implementation in Go. Did I miss anyone?
There is a v0.11 branch on github for this version.
Have something to write? Comment on this article.