r/lisp • u/Imaginary-Deer4185 • 9d ago
Code vs data
Hi, I have been reading up on Lisp for the last couple of days. I come from Java, but have also written a "toy" Forth that compiles to byte code on Arduino.
It seems to me that the memory model of Lisp, if based on CONS cells alone, means a lot of serial traversing. I tried to search for malloc-style memory management in Lisp, and came up mostly empty, with various commentators condemning this approach.
I realize the "code as data" is great for macros, which remind me of immediate words in Forth, but with the added advantage of potentially having the code following it available as a CONS data structure, upon which it can work, as part of the compile process.
Now, compiling Forth is very simple, because Forth is mostly "flat", whereas Lisp is nested, but in the combined interest of speed and readability (where Forth falls short), I wonder if there has been made Lisp implementations with full macro support (on CONS source tree data) but with malloc style data handling, for lookup by offset and memory efficiency?
My Forth targets the atmega328p with 2Kb of SRAM. To a certain extent the stack nature of Forth becomes "bearable" when writing code, but Lisp syntax is much more explicit. I am interested in mapping a Lisp parser/compiler onto the bytecode machine I have defined for my Forth-like language.
View all comments
5
u/Imaginary-Deer4185 3d ago
I hacked together a Lisp S-expression compiler in my forth toy language. I have created a "defun" word in Forth, but it doesn't take params, and there are no local variables. It rewrites an S-expr on form (fn A B C) into "A B C fn" forth style, recursively.
I also Implemented a setq word to get sensible order of parameters (its implementation is literally "swap !")
There also is a second form for inline S-expressions in Forth code, with LIsp[ .... ]
The progn and push words do nothing. The defun'ed functions become Forth words, and can call each other, or themselves, regular Forth words and "ops" like +-*/ etc. It is all compiled to my bytecode format.
The thing I struggled with the most was realizing that as the Lisp compiler runs in Forth on the microcontroller (over serial), I can't reliably send code with "defun" and "Lisp[...]" at the same speed as I send regular Forth files, since the "colon compiler" is written in C.
The Forth runtime chugs along at around 85-100k ops per second, on a 16MHz Arduino, so not the most efficient implementation, but the byte code is very economic on memory. The Lisp library in total, with dictionary entries and compiled code, consumes just 1013 bytes.
Great fun getting it to work. It remains to be seen if it is useful.