I was looking for some way to easily create, read, manipulate and print cyclic or recursive data structures in some programming languages, and got to the cool concept of sharp variables.
Manipulating Recursive Structures in Python
A straightforward way of defining a recursive structure is to first assign a base (non-recursive) structure to a variable, and then alter or extend that variable with a recursive expression. For example, in Python you can write:
That code will create a recursive data structure: [1, 2, 3, [1, 2, 3, [...]]],
or a = [1, 2, 3, a].
Actually, Python's print function lets you print a representation of a recursive structure without recursing indefinitely:
Python's pickle module lets you dump a recursive data structure into a file. You can also read that serialized structure from the file:
importpickle#dump it to fileoutput=open("out.pkl","wb")pickle.dump(my_rec_var,output)
However, there's no literal way of creating, reading or modifying that structure:
Manipulating Recursive Structures in Lisp
For manipulating/printing recursive data structures in Common Lisp we first assign T to the global variable *print-circle*
We can define a recursive structure just as we did with Python, by defining some base structure and then modifying the structure to be recursive:
(defvar*my-rec-var*(list123_));Replace the underscore placeholder with a self-reference(setf(fourth*my-rec-var*)*my-rec-var*)
The final structure is represented with sharp variables:
>>> (print *my-rec-var*)#1=(123#1#)
This is just as the "Mathematical" definition we gave above:
a = [1, 2, 3, a].
What's interesting about this "serialization format" is that expressions involving sharp variables are truly expressions: these "objects" can be read and manipulated just like any other structure:
Sharp variables seem like an excellent solution for creating, reading and manipulating cyclic data structures.